Worksheets.Add method

B

Bruce Lindsay

I have tried to add a worksheet with the following code.

dim oDoc as Workbook
dim oSht as Worksheet

Set oDoc = Application.ThisWorkbook
oSht = oDoc.Worksheets.Add

It gives an error #1004. I have tried it in many variations but all fail.
Some even create the sheet but still error out. Any help would be
appreciated.
 
R

Ron de Bruin

This will work Bruce

Dim oDoc As Workbook
Dim oSht As Worksheet

Set oDoc = Application.ThisWorkbook
oDoc.Worksheets.Add
 
K

Kevin Stecyk

Hi Bruce,

You just had a typo...

oSht = oDoc.Worksheets.Add

should be

Set oSht = oDoc.Worksheets.Add

HTH

Regards,
Kevin
 
J

J.E. McGimpsey

Try this variation:

Set oSht = oDoc.Worksheets.Add

Objects need to be assigned to variables with Set.
 
K

Kevin Stecyk

Sorry, ignore me and accept Ron's solution.


Kevin Stecyk said:
Hi Bruce,

You just had a typo...

oSht = oDoc.Worksheets.Add

should be

Set oSht = oDoc.Worksheets.Add

HTH

Regards,
Kevin
 
B

Bruce Lindsay

Thanks guys for your help. When I placed it in the code with nothing else it
works. However, if I add "after:=1 then it errors out. Thanks for the help.
 
J

J.E. McGimpsey

Please take a look at VBA Help for the Worksheets.Add method.

The After argument must be an object (i.e. a Sheet), not a value.

Try:

Set oSht = oDoc.Worksheets.Add(After:=Sheets(1))
 
R

Ron de Bruin

Try

Sub test()
Dim oDoc As Workbook
Dim oSht As Worksheet

Set oDoc = Application.ThisWorkbook
oDoc.Worksheets.Add after:=Sheets(1)
End Sub
 
T

Tom Ogilvy

Remember this two days ago?

Dim oDoc As Workbook
Dim oSht As Worksheet
Set oDoc = Application.ThisWorkbook
Set oSht = oDoc.Worksheets.Add(after:=oDoc.Worksheets(1))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top