如果强制SHeet名称存在,则运行macros

我有一个macros,它依赖于特定工作表名称“PRODUCTS45”的问题是,如果用户在不同的工作表上运行macros如Sheet1它会引发debugging错误。 任何人都可以帮助我只有当sheet'PRODUCTS45'存在时才运行macros,如果不存在msgbox,那么强制表不存在。

Option Explicit Sub FlagWord() Dim R As Range, WS As Worksheet Dim RE As Object Dim C As Range, D As Range Dim S As String Dim I As Long, J As Long S = InputBox("Enter desired word") 'Current filled in range Set WS = Worksheets("SHEET") 'case sensitive sheet name and its required to run macro if this is not present macro should not run With WS Set R = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)) Set R = R.Resize(columnsize:=.Cells(1, .Columns.Count).End(xlToLeft).Column) End With If Not S = "" Then 'If S not present then add column With WS.Rows(1) Set C = .Find(what:=S, after:=.Cells(1, 1), LookIn:=xlValues, _ lookat:=xlWhole, searchorder:=xlByColumns, searchdirection:=xlNext, MatchCase:=False) End With 'Add column if not already present If C Is Nothing Then Set R = R.Resize(columnsize:=R.Columns.Count + 1) R(1, R.Columns.Count) = S End If End If 'no new column if S is blank 'do the word match 'Clear the data area With R .Offset(1, 1).Resize(.Rows.Count - 1, .Columns.Count - 1).ClearContents End With 'fill in the data 'use regex to allow for easy word boundaries Set RE = CreateObject("vbscript.regexp") With RE .Global = False 'only need a single match .ignorecase = True For Each C In R.Columns(1).Offset(1, 0).Resize(R.Rows.Count - 1).Cells For Each D In R.Rows(1).Offset(0, 1).Resize(columnsize:=R.Columns.Count - 1).Cells .Pattern = "\b" & D.Text & "\b" If .test(C.Text) = True Then R(C.Row, D.Column) = "YES" End If Next D Next C End With End Sub 

怎么样这样的事情:

 Public Sub CheckForSheetBeforeCallingFlagWord() Dim ws As Worksheet Dim bolFound As Boolean bolFound = False For Each ws In ThisWorkbook.Worksheets If ws.Name = "PRODUCTS45" Then bolFound = True Next ws If bolFound = False Then MsgBox "Required sheet 'PRODUCTS45' not found." & Chr(10) & "Aborting..." Exit Sub End If Call flagword End Sub 

此过程检查是否存在所需的工作表。 如果没有find,那么你会得到一个消息框,没有其他的事情发生。 如果find工作表,则另一个过程被调用(并执行)。

尝试引用一个不存在的工作表会引发一个错误。 你可以使用一个error handling程序来捕获这个消息并给出所需的消息。

 Sub myMacro() On Error GoTo sheetNotFound doStuff ThisWorkbook.Sheets("PRODUCTS45") Exit Sub sheetNotFound: MsgBox "PRODUCTS45 not found" End Sub Sub doStuff(ws As Worksheet) ' remaining code goes here End Sub