麻烦引用图纸代码名称

这里有一个基本的问题:我正在写一个Excelmacros,我想使用工作表代码名来尝试消除任何错误。 我可以使用Sheet1的代码名称,它工作正常,但是当我尝试使用其他代码,如Sheet3或Sheet7编辑器不能识别它们,如果我运行macrosExcel启动了一个错误告诉我,我的“variables未定义“。

例如:

Option Explicit Sub Test() Dim SheetObject As Worksheet Dim SheetObject2 As Worksheet Set SheetObject = Sheet1 Set SheetObject2 = Sheet3 MsgBox (SheetObject.Name) MsgBox (SheetObject2.Name) End Sub 

如果我注释掉任何引用SheetObject2的代码,macros就会正确运行。 如果我把它们放进去,我会得到错误。 我绝对有一个Sheet3,代码名称绝对是Sheet3。 我整天环顾Google,似乎无法提出任何解决scheme,任何帮助都会很棒。

提前致谢,

杰西

我最后一个雇主收集数据并创build了国家统计 大部分数据都是以Excel工作簿的forms出现的,所以我有很多相关的经验。

如果你正在运行自己的macros,如果这是一次性练习,那么这样的testing可能是足够的:

 Debug.Assert WbookTgt.WsheetTgt.Range("A1").Value = "Date" 

许多语言都有一个Assert语句作为发展援助; 这是VBA版本。 如果断言不正确,macros将停止,并突出显示此语句。

如果这种方法不够,应考虑开发执行检查和更新任务的参数化macros。 我已经浏览了一些旧的macros,但大部分对于VBA新手来说是不可理解的。 我已经提取代码来创build两个macros,我希望能给你一些想法。

macros1 – OpenWorkbook

定期提供数据的组织通常使用诸如“Xxxxx 1409.xlsx”和“Xxxxx 1410.xlsx”之类的名称,用于9月和10月版本的数据。 例如,您可以每个月更新一次macros的最新名称,或者将文件名更改为标准值。 这两种可能性之一都是令人讨厌的,我会特别反对第二种想法,因为我喜欢将我所处理的所有工作簿存档。

OpenWorkbook()使用Dir语句在文件夹中search匹配模板(如“Xxxxx * .xls *”)的文件。 如果单个文件与此模板匹配,macros将打开工作簿并返回对其的引用。

macros2 – CheckWorksheets

您可能已经注意到一些VBA例程具有固定数量的参数,而其他VBA例程具有可变数量的参数。 例如,以下是CheckWorksheets的所有有效调用:

 If CheckWorksheets(WbookTgt, WbookThis, “Name1”) then If CheckWorksheets(WbookTgt, WbookThis, “Name1”, “Name2”) then If CheckWorksheets(WbookTgt, WbookThis, “Name1”, “Name2”, “Name3”) then 

CheckWorksheets有三个参数。 前两个是工作簿参考。 第三个是ParamArray SheetName() As Variant 。 前两个之后的任何参数都放在数组SheetName中,这个数组可以是必要的。 这里所有的尾部参数都是string,但是它们可以是任何types的。

我可以使用OpenWorkbook打开本月版本的源文件,然后使用CheckWorksheets确认我的macros所需的所有工作表都存在。

工作表错误“

这两个macros需要工作表错误出现在指定的工作簿中。 如果macros检测到错误,则会向此工作表添加详细的错误消息。 我发现这是一个方便的技术来捕获任何错误的细节。

macrosDemo1和Demo2

我已经包含了两个macros,这些macros在我的系统上演示了这些macros与工作簿的用法。 如果您修改Demo1和Demo2以在一些工作簿上进行操作,您应该了解OpenWorkbook和CheckWorksheets可以为您做些什么。

根据需要回答问题,但是您可以自己解密OpenWorkbook和CheckWorksheets的速度越快,开发自己的技能的速度就越快

 Option Explicit Sub Demo1() Dim Path As String Dim WbookThis As Workbook Dim WbookTgt As Workbook ' Application.ThisWorkbook identifies the workbook containing this macro. Set WbookThis = Application.ThisWorkbook ' I find it convenient to place my target workbooks in the folder ' holding the workbook containing the macro(s). Path = WbookThis.Path Set WbookTgt = OpenWorkbook(Path, "Combined*.xls*", WbookThis) If WbookTgt Is Nothing Then ' Detailed error message already recorded in "Errors" Call MsgBox("Wokbook failed checks", vbOKOnly) Else With WbookTgt Debug.Print .Path & "\" & .Name & " opened." .Close SaveChanges:=False End With End If End Sub Sub Demo2() Dim Path As String Dim WbookThis As Workbook Dim WbookTgt As Workbook ' Application.ThisWorkbook identifies the workbook containing this macro. Set WbookThis = Application.ThisWorkbook ' I find it convenient to place my target workbooks in the folder ' holding the workbook containing the macro(s). Path = WbookThis.Path Set WbookTgt = OpenWorkbook(Path, "Combined 2.04.xls*", WbookThis) If WbookTgt Is Nothing Then ' Detailed error message already recorded in "Errors" Call MsgBox("Wokbook failed checks", vbOKOnly) Exit Sub End If With WbookTgt If Not CheckWorksheets(WbookTgt, WbookThis, "Critical Path", "Dyn Dims") Then Call MsgBox("Wokbook failed checks", vbOKOnly) .Close SaveChanges:=False Exit Sub End If Debug.Print .Path & "\" & .Name & " contains worksheets Critical and Dym Dims" .Close SaveChanges:=False End With End Sub Function CheckWorksheets(ByRef WbookTgt As Workbook, ByRef WbookError As Workbook, _ ParamArray SheetName() As Variant) As Boolean ' * Return True if WbookTgt contains every specified worksheet. ' * WbookTgt is the workbook to be checked ' * WbookError identifies the workbook containing worksheet "Error" to which any ' error message will be added. ' * SheetName() is an array of worksheet names. Dim ErrorMsg As String Dim FoundError As Boolean Dim FoundSheet() As Boolean Dim FoundSheetsCount As Long Dim InxName As Long Dim InxWsheet As Long Dim NotFoundSheetsCount As Long Dim RowErrorNext As Long Dim SheetNamesFound As String ' Size FoundSheet to match SheetName. Array elements initialised to False ReDim FoundSheet(LBound(SheetName) To UBound(SheetName)) FoundSheetsCount = 0 NotFoundSheetsCount = 0 With WbookTgt For InxName = LBound(SheetName) To UBound(SheetName) NotFoundSheetsCount = NotFoundSheetsCount + 1 ' Assume not found until found For InxWsheet = 1 To .Worksheets.Count If SheetName(InxName) = .Worksheets(InxWsheet).Name Then FoundSheet(InxName) = True FoundSheetsCount = FoundSheetsCount + 1 NotFoundSheetsCount = NotFoundSheetsCount - 1 Exit For End If Next Next End With If NotFoundSheetsCount = 0 Then CheckWorksheets = True Exit Function End If SheetNamesFound = "" ErrorMsg = WbookTgt.Path & "\" & WbookTgt.Name & " does not contain " If NotFoundSheetsCount = 1 Then ErrorMsg = ErrorMsg & "this expected worksheet:" Else ErrorMsg = ErrorMsg & "these expected worksheets:" End If For InxName = LBound(SheetName) To UBound(SheetName) If Not FoundSheet(InxName) Then ErrorMsg = ErrorMsg & vbLf & " " & SheetName(InxName) Else SheetNamesFound = SheetNamesFound & vbLf & " " & SheetName(InxName) End If Next If FoundSheetsCount = 0 Then ' No need to add list of found sheet names Else ErrorMsg = ErrorMsg & vbLf & "but does contain " If FoundSheetsCount = 1 Then ErrorMsg = ErrorMsg & "this expected worksheet:" Else ErrorMsg = ErrorMsg & "these expected worksheets:" End If ErrorMsg = ErrorMsg & SheetNamesFound End If With WbookError With .Worksheets("Errors") RowErrorNext = .Cells(Rows.Count, "A").End(xlUp).Row + 1 With .Cells(RowErrorNext, "A") .Value = Now() .VerticalAlignment = xlTop End With .Cells(RowErrorNext, "B").Value = ErrorMsg End With End With CheckWorksheets = False End Function Function OpenWorkbook(ByVal Path As String, ByVal FileTemplate As String, _ ByRef WbookError As Workbook) As Workbook ' * If Path & FileTemplate identifies a single workbook, open it and return ' it as an object. If Path & FileTemplate does not represent a single ' workbook, report the problem in worksheet Errors and return Nothing. ' * WbookError identifies the workbook containing worksheet "Error". ' * Path must be the name of the folder in which the required workbook is located ' * FileTemplate can either be a specific filename or can contain wild cards ' providing only one file matches the template. ' * WbookError identifies the workbook containing worksheet "Error" to which any ' error message will be added. Dim ErrorMsg As String Dim FileNameCrnt As String Dim FileNameMatch As String Dim RowErrorNext As Long FileNameMatch = Dir$(Path & "\" & FileTemplate, vbNormal) If FileNameMatch = "" Then ' No matches found ErrorMsg = "Template " & Path & "\" & FileTemplate & " does not match any file" Else ' At least one match. ' If only one match, its name is in FileNameMatch Do While True FileNameCrnt = Dir$ If FileNameCrnt = "" Then ' No more matches Exit Do End If ' A second or subsequent match has been found. If FileNameMatch <> "" Then ' This is the second match. ' Initialise error message and report name of first match ErrorMsg = "Template " & Path & "\" & FileTemplate & " matches more than one file:" & _ vbLf & " " & FileNameMatch FileNameMatch = "" ' No single match End If ' Add name of current match to error message ErrorMsg = ErrorMsg & vbLf & " " & FileNameCrnt Loop End If If FileNameMatch = "" Then ' No single match found. ' ErrorMsg contains an appropriate error message With WbookError With .Worksheets("Errors") RowErrorNext = .Cells(Rows.Count, "A").End(xlUp).Row + 1 With .Cells(RowErrorNext, "A") .Value = Now() .VerticalAlignment = xlTop End With .Cells(RowErrorNext, "B").Value = ErrorMsg Set OpenWorkbook = Nothing End With End With Else ' Single match found Set OpenWorkbook = Workbooks.Open(Path & "\" & FileNameMatch) End If End Function 

回答额外的问题

VBA没有什么比VB的Try更方便,但它在程序员控制下确实有一些error handling。

如果您使用如下命令:

 Worksheets("Sheet2").Delete 

用户将被要求确认删除。 为了避免这种情况,使用:

 Application.DisplayAlerts = False Worksheets("Sheet2").Delete Application.DisplayAlerts = True 

我在macros的开始处看到Application.DisplayAlerts = False代码,这意味着即使程序员不期望它也不会显示提醒用户的注意。 通过包围Delete ,我确保只有我期待的警报被压制。

考虑:

 Sub OpenFile() Dim InputFileNum As Long InputFileNum = FreeFile Open "Dummy.txt" For Input As InputFileNum Debug.Print "File successfully opened" Close InputFileNum End Sub 

文件“Dummy.txt”不存在,因此macros将停止在Open语句。

你有时会看到这样的代码:

 Sub OpenFile() Dim InputFileNum As Long On Error GoTo ErrorCode InputFileNum = FreeFile Open "Dummy.txt" For Input As InputFileNum Call MsgBox("File successfully opened", vbOKOnly) Close InputFileNum Exit Sub ErrorCode: Debug.Print "Unexpected error: " & Err.Number & " " & Err.Description End Sub 

在这里,我提供了一个可能发生的任何错误条件的一般处理程序。 我不赞成,虽然我接受这个比非技术用户看到错误的陈述突出显示稍好。 麻烦的是任何错误都会导致相同的无用的错误信息。

我从不在开发过程中包含error handling。 如果发生错误,我希望macros停止在错误的语句,所以我可以考虑如何避免错误。 在这里,我应该试图打开它之前检查文件存在。 我更喜欢这样的事情:

 Sub OpenFile() Dim FileSysObj As Object Dim InputFileNum As Long On Error GoTo ErrorCode Set FileSysObj = CreateObject("Scripting.FileSystemObject") If Not FileSysObj.FileExists("Dummy.txt") Then Call MsgBox("I am unable to find ""Dummy.txt"". List of helpful suggestions.", vbOKOnly) Exit Sub End If InputFileNum = FreeFile Open "Dummy.txt" For Input As InputFileNum Call MsgBox("File successfully opened", vbOKOnly) Close InputFileNum Exit Sub ErrorCode: Debug.Print "Unexpected error: " & Err.Number & " " & Err.Description End Sub 

我已经包括检查错误,我期望的代码。 如果该文件不存在,我已经显示了一条消息,希望能够帮助用户解决问题。

有时你无法避免一个错误。 为了testing下面的代码,我创build了文件Dummy.txt,但设置了“读访问被拒绝”标志。 (据我所知)没有简单的方法来testingVBAmacros。 我有一个意外错误的一般处理程序,但我打开它的名称,所以我可以包含特定的代码打开失败。 我已经删除了使用FileExists()来testingDummy.txt是否存在的代码,因为与其他打开的文件错误testing相比,它更容易。

 Sub OpenFile() Dim FileSysObj As Object Dim InputFileNum As Long On Error GoTo ErrorCode ' General handler for unexpected errors InputFileNum = FreeFile Err.Clear On Error Resume Next ' Record error in Err object and continue Open "Dummy.txt" For Input As InputFileNum Select Case Err.Number Case 0 ' No error. Case 53 ' File does not exist Call MsgBox("I am unable to find ""Dummy.txt"". List of helpful suggestions.", vbOKOnly) Exit Sub Case 75 ' Path/File access error Call MsgBox("It appears file ""Dummy.txt"" exists but I do not have permission to read it.", vbOKOnly) Exit Sub Case Else Call MsgBox("My attempt to open ""Dummy.txt"" failed with an unexpected error condition" & vbLf & _ " " & Err.Number & " " & Err.Description, vbOKOnly) Exit Sub End Select On Error GoTo ErrorCode ' Restore general handler for unexpected errors Call MsgBox("File successfully opened", vbOKOnly) Close InputFileNum Exit Sub ErrorCode: Debug.Print "Unexpected error: " & Err.Number & " " & Err.Description End Sub 

访问http://support.microsoft.com/kb/146864查看一长串错误代码以及有关error handling的更多信息。