将自定义错误消息添加到Excelmacros
下面的macros打开一个Excel工作簿,并在提供的数据上build立一个图表。 我想添加一些error handling,以便在提供与指定的名称(Employee_source_data)名称不同的Excel工作簿时,会显示一个消息框,例如,请确保提供的电子表名称是“Employee_source_data”。 任何想法如何做到这一点? 提前致谢!
Sub GenerateEmployeeReport() Workbooks.Open Filename:=ThisWorkbook.Path & "\Employee_source_data" Range("E2").Select ActiveCell.FormulaR1C1 = "=SUM(RC[-3]:RC[-1])" Selection.AutoFill Destination:=Range("E2:E7"), Type:=xlFillDefault Range("E2:E7").Select Range("A1:A7,E1:E7").Select Range("E1").Activate ActiveSheet.Shapes.AddChart.Select ActiveChart.SetSourceData Source:=Range( _ "'Sheet2'!$A$1:$A$7,'Sheet2'!$E$1:$E$7") ActiveChart.ChartType = xl3DColumnClustered End Sub
Dir()函数将派上用场。
尝试类似
if dir(ThisWorkbook.path & "Employee_source_data*") = "" then msgbox "Please ensure spreadsheet name provided is Employee_source_data" end if
另一种方法是使用FileDialog控件,如果你处于更容易让它们select的状态。 根据我的经验,没有人坚持命名约定,而不是强制执行。
Sub GenerateEmployeeReport() Dim strWorkbookName As String Dim Answer As String Start: strWorkbookName = InputBox("Enter Workbook", "Open Workbook") On Error GoTo BadWorkbook Workbooks.Open Filename:=ThisWorkbook.Path & "\" & strWorkbookName Range("E2").Select ActiveCell.FormulaR1C1 = "=SUM(RC[-3]:RC[-1])" Selection.AutoFill Destination:=Range("E2:E7"), Type:=xlFillDefault Range("E2:E7").Select Range("A1:A7,E1:E7").Select Range("E1").Activate ActiveSheet.Shapes.AddChart.Select ActiveChart.SetSourceData Source:=Range( _ "'Sheet2'!$A$1:$A$7,'Sheet2'!$E$1:$E$7") ActiveChart.ChartType = xl3DColumnClustered Exit Sub BadWorkbook: Answer = MsgBox("Please ensure spreadsheet name provided is Employee_source_data", vbRetryCancel) If Answer = 4 Then GoTo Start Else: Exit Sub End If End Sub
goto命令将代码跳转到行标题WrongWorkbook
并为用户提供退出或继续msgbox rety取消button的机会。 然后如果他们重试它重新启动子启动,其他明智的退出