开发者

Concatenating Variables Into String to be Set to a Range in VBA

开发者 https://www.devze.com 2023-03-25 03:15 出处:网络
I am having a problem with a particular line of code: ActiveSheet.Range(\"A\" & rowCount & \":\" & Mid(alphabet, totHdrLngth, 1) & belowRowCount)

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 "inRa开发者_运维知识库nge" 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消