5

I am new to Excel VBA. I need a modification in my code so that I would be able to proceed further.

I want to select multiple table columns in an excel table. Here is my code:

Dim ws As Worksheet
Dim tbl As ListObject

Set ws = Sheets("Sheet1")
Set tbl = ws.ListObjects(1)

Range("tbl[[Column1]:[Column5]]").Select

When I put the table name, it works. but I want to use variable which I have used in my code to select the table columns.

Adam B
  • 3,775
  • 3
  • 32
  • 42
Salman Khan
  • 131
  • 1
  • 2
  • 11

2 Answers2

4

You can use concatenation to use a variable as a table name.

Here is the code:

Dim ws As Worksheet
Dim tbl As ListObject

Set ws = Sheets("Sheet1")
Set tbl = ws.ListObjects(1)

Range(tbl & "[[Column1]:[Column5]]").Select
1

Welcome to Stackoverflow!

There are many ways to do this:

you could use:

Range("A:E").Select ' example selects columns from A to E

Otherwise you could also make it by using an array example:

Sub test()

 Dim x, y As Range, z As Integer
    x = Array(1, 5)
    Set y = Columns(x(0))
    For z = 1 To UBound(x)
        Set y = Union(y, Columns(x(z)))
    Next z
    y.Select
  End Sub

but this depends of what you needs

Best regards

Daniel

XsiSecOfficial
  • 954
  • 8
  • 20