Option Explicit
Sub Test_xlSheetExists()
' Demonstration: demonstrates the use of xlSheetExists; prompts user for workbook
' name and worksheet name, and displays return from xlSheetExists
' (0, 1, 2)
Dim xlRtn As Integer
Dim xlBookName As String, xlSheetName As String, MsgTitle As String
MsgTitle = "Demo of xlSheetExists"
'
' prompt user for workbook name
'
xlBookName = InputBox("enter name of workbook to be tested." & vbCrLf & _
"[leave empty for active workbook]" & vbCrLf & _
"[name is not case sensitive]", MsgTitle)
'
' prompt user for sheet name
'
xlSheetName = InputBox("enter name of sheet to be tested." & vbCrLf & _
"[name is not case sensitive]", MsgTitle)
If xlSheetName = "" Then Exit Sub
'
' test xlBookName.xlSheetName
'
xlRtn = xlSheetExists(xlSheetName, xlBookName)
'
' display book name, sheet name and return from xlSheetExists
'
If xlBookName = "" Then xlBookName = ActiveWorkbook.Name
Select Case xlRtn
Case 0
MsgBox "chart or sheet name entered = " & xlSheetName & vbCrLf & _
"xlBookName entered (or implied) = " & xlBookName & vbCrLf & _
xlSheetName & " does not exist", _
vbInformation & vbOKOnly, MsgTitle
Case 1
MsgBox "chart or sheet name entered = " & xlSheetName & vbCrLf & _
"xlBookName entered (or implied) = " & xlBookName & vbCrLf & _
xlSheetName & " is a worksheet", _
vbInformation & vbOKOnly, MsgTitle
Case 2
MsgBox "chart or sheet name entered = " & xlSheetName & vbCrLf & _
"xlBookName entered (or implied) = " & xlBookName & vbCrLf & _
xlSheetName & " is a chartsheet", _
vbInformation & vbOKOnly, MsgTitle
End Select
End Sub
Function xlSheetExists(SheetName As String, Optional WorkBookName As String) As Integer
' Function: tests if SheetName is the name of any type of sheet in
' the target workbook. Function value of proc on return:
' 0 not the name of a recognized sheet type
' 1 traditional worksheet
' 2 chart sheet
'
Dim xlobj As Object
'
' test for WorkBookName, if null, use ActiveWorkBook name
'
If WorkBookName = vbNullString Then WorkBookName = ActiveWorkbook.Name
'
' test for worksheet
'
On Error Resume Next
Set xlobj = Workbooks(WorkBookName).Worksheets(SheetName)
If Err = 0 Then ' is work sheet
xlSheetExists = 1
Exit Function
End If
'
' test for chart sheet
'
On Error Resume Next
Set xlobj = Workbooks(WorkBookName).Charts(SheetName)
If Err = 0 Then ' is chart sheet
xlSheetExists = 2
Exit Function
End If
'
' neither chart nor work sheet, set function value
' to zero
'
xlSheetExists = 0
End Function
|