I’m trying to dynamically transpose a Recordset over a Range in Excel using VBA. I can do the transposition succesfully when I give it a static range such as this:
Range("A1:C16").Select
Range("A1:C16").Value = Application.WorksheetFunction.Transpose(scores)
When I try to use an equivalent string and pass it in to the Range function, however, it fails. My variable trange when printed out is “A1:C16” (including the double quotes). The reason I need to pass it a string is because the string is derived from a length variable which could be any value.
This code below fails:
Dim trange As String
trange = """A1:C" & slength & """"
MsgBox (trange)
Range(trange).Select
Range(trange).Value = Application.WorksheetFunction.Transpose(scores)
Unfortunately, escaping double quotes in VBA is ugly and that’s why my trange assignment expression looks strange but when I MsgBox it, it is in fact giving me the correct value.
Using string concatenation to construct range addresses is a bad idea. It’s messy and error-prone (as your example illustrates!).
Instead of
Range("A1:C16"), you can say any of the following:There are probably more possibilities. The key is that none of them involve string concatenation.
Replace
16byslengthin any of the examples above to make your variable-size range.Also, it’s good practice specify what worksheet you’re referring to. Instead of plain
Range(anything), use e.g.or even better,