![]() |
![]() |
|
|||||||
| Excel Questions All Excel/VBA questions - formulas, macros, pivot tables, general help, etc. Please post to this forum in English only. |
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Board Regular
Join Date: Apr 2002
Location: Alberta, Canada
Posts: 50
|
I need to create a macro that will search my workbook for sheet "Data" and if there is no sheet called "Data" then create a new sheet and name it Data. If Data is present then the macro does nothing. Any suggestions?
|
|
|
|
|
|
#2 |
|
MrExcel MVP
Join Date: Mar 2002
Location: Chicago, IL USA
Posts: 2,042
|
The routine Add_Data_Sheet() calls a private function SheetExists, so both are required.
Code:
Sub Add_Data_Sheet()
If SheetExists("Data") = False Then
Worksheets.Add After:=Sheets(ThisWorkbook.Worksheets.Count)
ActiveSheet.Name = "Data"
End If
End Sub
Private Function SheetExists(sheetname) As Boolean
Dim abc As Object
On Error Resume Next
Set abc = ActiveWorkbook.Sheets(sheetname)
If Err = 0 Then SheetExists = True _
Else SheetExists = False
End Function
|
|
|
|
|
|
#3 |
|
Board Regular
Join Date: Apr 2002
Location: Alberta, Canada
Posts: 50
|
i get a compile error: else without if with
Else: SheetExists = False |
|
|
|
|
|
#4 |
|
MrExcel MVP
Join Date: Mar 2002
Location: Chicago, IL USA
Posts: 2,042
|
I cannot replicate your error.
Try to rewrite it as: Code:
If Err = 0 Then
SheetExists = True
Else
SheetExists = False
End If
|
|
|
|
|
|
#5 |
|
MrExcel MVP
Join Date: Mar 2002
Location: Chicago, IL USA
Posts: 2,042
|
I *can* replicate it.
You need to insert an underscore at the end of the first line, as this is actually only one line. If Err = 0 Then SheetExists = True Else SheetExists = False [ This Message was edited by: Jay Petrulis on 2002-05-03 14:29 ] |
|
|
|
|
|
#6 |
|
Board Regular
Join Date: Apr 2002
Location: Alberta, Canada
Posts: 50
|
both those worked. thanks
|
|
|
|
![]() |
| Bookmarks |
| Thread Tools | |
| Display Modes | |
|
|