1

I have a excel macro which reads content from a specific column in another sheet. I want to use a variable in the sheet name in a WITH statement but keep getting an error message "Error during runtime, Object required" in the For Each line

I already searched how to use variables in object names and tried that, but to no avail.

This code works

With Blad2
strData = Range(id & "1") & vbLf & vbLf
    For Each c In .Range(id & "2:" & id & "10")
        If c.Value <> "" Then
            strData = strData & " - " & c.Value & vbLf
        End If
    Next c
End With

This code fails. I know for sure variable bld has a numeric value, tested that with MsgBox

With ("Blad" & bld)
strData = Range(id & "1") & vbLf & vbLf
    For Each c In .Range(id & "2:" & id & "10")
        If c.Value <> "" Then
            strData = strData & " - " & c.Value & vbLf
        End If
    Next c
End With

Any clues how I can get this to work?

Jeroen Swets
  • 215
  • 1
  • 6
  • 17

2 Answers2

3

A worksheet could be referred to in 4 ways:

  • with its index;
  • with its Name on the tab;
  • with its CodeName, which is by default the same as the name of the tab, unless the latter is changed;
  • with a variable;

Some time ago I have written this answer here - https://stackoverflow.com/a/52721327/5448626


When you write With Blad2, then Blad2 is the codename of the worksheet. E.g., the one here:

enter image description here

Thus, it is already a variable and Excel recognizes it. On the other hand, With ("Blad" & bld) is a string and not a worksheet variable.

To make it work, use With Worksheets("Blad" & bld), using the worksheet name of the worksheet.

Vityata
  • 42,633
  • 8
  • 55
  • 100
2

What you are trying is to use Variable Variable for SheetCode Name. You cannot do it like that. To achieve what you want, try this...

Dim bld As Long: bld = 2
Dim shtCode As String

shtCode = "Blad" & bld

With Sheets(ThisWorkbook.VBProject.VBComponents(shtCode).Properties("Name").Value)
    Debug.Print .Name
End With
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250