Concatenating Variables Into String to be Set to a

2019-02-26 21:08发布

问题:

I am having a problem with a particular line of code:

ActiveSheet.Range("A" & rowCount & ":" & Mid(alphabet, totHdrLngth, 1) & belowRowCount)

Where alphabet is a string containing uppercase letters A to Z.

I keep getting the following error:

Run-time error '5':
Invalid Procedure call or argument

I tried creating a String "inRange" and changing the code to this:

inRange = "A" & rowCount & ":" & Mid(alphabet, totHdrLngth, 1) & belowRowCount
curRange = ActiveSheet.Range(inRange)

But that did not help (as I thought it wouldn't). Any suggestions?

回答1:

Although creating ranges like this is frowned upon in general, the way to do it is with the word SET (like @Gary McGill stated in the comments). Here is an example of how to do this:

Sub test()

Dim alphabet As String
Dim totHrdrLngth As Long
Dim belowRowCount As Long
Dim rowCount As Long
Dim inRange As Range

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
totHrdrLngth = 5
belowRowCount = 10
rowCount = 5

' Gives us A5:E10
Set inRange = Range("A" & rowCount & ":" & range2 & _
                    Mid$(alphabet, totHrdrLngth, 1) & belowRowCount)

End Sub

You are running this macro in the current range, so there should be no need to specify ActiveSheet.Range. I hope this helps get you toward what you are trying to achieve.



回答2:

As far as I can tell, you're getting an error because your types don't match up. I imagine rowCount is an integer, as is belowRowCount. If you convert them to strings before concatenating them, you can fix it. str() will convert an integer to a string with a space before it, and LTrim() will remove the space. Try code as below:

Dim sRowCount As String
Dim sBelowRowCount As String

and later

sRowCount = LTrim(Str(RowCount))
sBelowRowCount = LTrim(Str(belowRowCount))

inRange = "A" & sRowCount & ":" & Mid(alphabet, totHdrLngth, 1) & sBelowRowCount
curRange = ActiveSheet.Range(inRange)

Hope this helps.