下面的宏打开了一个excel工作簿,并根据提供的数据构建了一个图表。我想添加一些错误处理,以便在提供与指定的(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
答案 0 :(得分:1)
Dir()函数会派上用场 尝试像
这样的东西if dir(ThisWorkbook.path & "Employee_source_data*") = "" then
msgbox "Please ensure spreadsheet name provided is Employee_source_data"
end if
另一种方法是使用FileDialog控件,如果您处于更容易让他们选择它的情况下。根据我的经验,没有人坚持命名惯例而不是强制执行。
答案 1 :(得分:1)
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取消按钮。然后如果他们重试它,用goto start重新启动sub,否则它退出