Sculpt

Professional Excel development

Check a worksheet exists in a specified workbook

leave a comment »

When opening a specified workbook, you may need to check that it contains a particular worksheet. First open the workbook – to do this, we’ll use the File Dialog picker. The code below opens the File Dialog, then opens the selected workbook.

___________________________________

Sub OpenFile()

Dim OpenFileName As Variant

OpenFileName = Application.GetOpenFilename() ‘Opens the File Dialog
If OpenFileName = False Then Exit Sub ‘If no file selected
Workbooks.Open (OpenFileName)
Call WorksheetCheck(OpenFileName) ‘Check if worksheet exists
ActiveWorkbook.Close False

End Sub

___________________________________

The sub WorksheetCheck(OpenFileName) checks to see if the specified worksheet – “Data” – exists in the selected workbook. For this we need a new sub and a function – specify the name of the worksheet you’re checking for in the new sub. The function simply returns a True/ False to the sub, then displays a message box.

___________________________________

Sub WorksheetCheck(OpenFileName)

If SheetExists(“Data”) = True Then
MsgBox (“The worksheet exists”)
Else
MsgBox (“The worksheet doesn’t exist”)
End If

End Sub
___________________________________

Function SheetExists(SheetName As String) As Boolean
‘ True if worksheet exists in selected workbook
SheetExists = False
On Error GoTo NoSuchSheet

If Len(Sheets(SheetName).Name) > 0 Then
SheetExists = True
Exit Function
End If

NoSuchSheet:

End Function

___________________________________

Advertisement

Written by Austin

January 22, 2007 at 9:16 pm

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.