Use VBA to Create Table with Unkown Range

ABlohm

New Member
Joined
Mar 16, 2017
Messages
5
I would like to create a table with an unknown range. I currently have the following.

Sub Button2_Click()

Dim r As Range


Set r = Worksheets("Sheet2").Range("A1").CurrentRegion

Worksheets("Sheet2").ListObjects.Add(xlSrcRange, Range("A1:B4"), xlYes).Name = "MyTable"

End Sub

An example of the Excel data on Sheet 2.

Job Position Time
V1 10
V2 11
V3 12

What I have above does not work. It will work if Range() has Range("A1:B4"). I thought that if I defined r as a range, it will substitute "A1:B4" in Range().

I receive a Run Time Error 1004 and Method Range of Object Global Failed.
 

Excel Facts

How to find 2nd largest value in a column?
MAX finds the largest value. =LARGE(A:A,2) will find the second largest. =SMALL(A:A,3) will find the third smallest
You'll need to replace Range("A1:B4") with r. Also, since you're not using named arguments, you'll need to place an additional comma for the third missing argument. Therefore, try...

Code:
[COLOR=darkblue]Sub[/COLOR] Button2_Click()

    [COLOR=darkblue]Dim[/COLOR] r [COLOR=darkblue]As[/COLOR] Range
    
    [COLOR=darkblue]Set[/COLOR] r = Worksheets("Sheet2").Range("A1").CurrentRegion
    
    Worksheets("Sheet2").ListObjects.Add(xlSrcRange, r, , xlYes).Name = "MyTable"

[COLOR=darkblue]End[/COLOR] [COLOR=darkblue]Sub[/COLOR]

To use named arguments...

Code:
[COLOR=darkblue]Sub[/COLOR] Button2_Click()

    [COLOR=darkblue]Dim[/COLOR] r [COLOR=darkblue]As[/COLOR] Range
    
    [COLOR=darkblue]Set[/COLOR] r = Worksheets("Sheet2").Range("A1").CurrentRegion
    
    Worksheets("Sheet2").ListObjects.Add(SourceType:=xlSrcRange, Source:=r, XlListObjectHasHeaders:=xlYes).Name = "MyTable"

[COLOR=darkblue]End[/COLOR] [COLOR=darkblue]Sub[/COLOR]

Hope this helps!
 
Upvote 0

Forum statistics

Threads
1,223,228
Messages
6,170,871
Members
452,363
Latest member
merico17

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top