Friday, 20 July 2012

Use Excel/Access VBA to check if sheet exists

Does a worksheet exist? Here is a simple way to test, so you can use it in your VBA or macro for Microsoft Excel or Access.
Put this function somewhere in your modules so that it can be used in your Sub():


Function SheetExists(wksName As String, wbk As Excel.Workbook) As Boolean
SheetExists = False
On Error GoTo thereisnosheet
'If the sheet isn't there, this IF will throw an error and be caught
If Len(Sheets(wksName).Name) > 0 Then
    SheetExists = True
    Exit Function
End If
thereisnosheet:
End Function

To check if a sheet exists on your declared workbook:

If SheetExists(c & "_O", wbk) = False Then
   'do some cool stuff
Else
   'Do something different - maybe create the sheet?
End If

Notice that you need to be working with a workbook already, such as by opening one like this:

Dim wbk As Excel.Workbook
Set wbk = Excel.Workbooks.Open("U:\Excel analysis\Weekday profiles.xlsm")
Excel.Application.Visible = True

No comments:

Post a Comment