Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create New Worksheet if not already there 1

Status
Not open for further replies.

DrSimon

IS-IT--Management
Dec 14, 2001
674
GB
Working from Access, I'd like to be able to open a spreadsheet (know how to do that) and then insert a new worksheet if one of that name doesn't already exist. The logic being something like:
If not exists xx.Sheets("Feb06") then Insert xx.Sheets("Feb06")
Any advice would be very useful.
 
DoCmd.TransferSpreadSheet creates/recreates a worksheet named after the query or table that you are exporting but doesn't remove any existing worksheets from the workbook (.xls file) so it will probably do what you want without the need to open Excel. All you need to do is create a query with the required name.



Bob Boffin
 
Good point Bob, but what I wanted to do was check the existing spreadsheet first just in case and also write to specific cells rather than 'dump' a table to Excel.

Simon Rouse
 
If you call for that sheet name then there is an error. In such a case add a new worksheet at the end and name it!

Code:
Dim objWrkbook As Object
Dim objSheet As Object
Dim yoursheetname As String

yoursheetname = "dd"
Set objWrkbook = ActiveWorkbook 'you know this
On Error Resume Next 
Set objSheet = objWrkbook.Sheets(yoursheetname)
If Err <> 0 Then
    objWrkbook.Worksheets.Add.Move after:=objWrkbook.Worksheets(Worksheets.Count)
    objWrkbook.Worksheets(Worksheets.Count).Name = yoursheetname
End If
On Error GoTo 0
 
Thanks JerryKlmns, just what I wanted.

Simon Rouse
 
I use this with a lot of different collections

Public Function fncUniqueName(theNewName As String, theCollection As Object) As Boolean
Dim Item As Object
fncUniqueName = True
For Each Item In theCollection
If theNewName = Item.Name Then
fncUniqueName = False
Exit Function
End If
Next Item
End Function
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top