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

Links? Where??
If Excel says you have links but you can't find them, go to Formulas, Name Manager. Look for old links to dead workbooks & delete.
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,215,993
Messages
6,128,175
Members
449,429
Latest member
ianharper68

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