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

…衆ロ難τιáo~ 提交于 2019-12-02 01:35:14

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!