excel - 工作表名称与目标工作表名称不匹配时的 VBA 运行时错误 9
问题描述
我有以下代码将具有特定工作表名称的 Excel 工作表转换为 PDF,然后在文件夹中循环。用户可以将工作表名称输入到工具中以供循环使用的代码。但是,如果工作表名称不正确或不存在,则会显示运行时错误 9:下标超出范围。而不是这个错误,我想得到一个 MsgBox 然后退出 Sub。我尝试使用 On Error GoTo 方法,当代码与工作表名称不匹配参考单元格并显示适当的消息时,该方法有效。但是,当插入正确的工作表名称时,它会显示该消息并且也不会继续执行代码。
我该如何解决这个问题,所以我只会在代码找不到工作表名称时收到消息,如果找到,它会完成代码?
这就是我面临的问题
On Error GoTo ErrorExit
'Even when the cell value matches the sheet's name, I still get an error and it exist the sub
Set reportSheet = Sheets(reportSheetName)
ErrorExit:
MsgBox "Incorrect Sheet Name or It Does Not Exist"
Exit Sub
Dim settingsSheet As Worksheet 'Source
Dim reportSheet As Worksheet 'To convert to PDF
Dim targetColumnsRange As Range 'feeds from source
Dim targetRowsRange As Range
Dim reportSheetName As String 'source sheet with the target's sheet name
Dim reportColumnsAddr As String
Dim reportRowsAddr As String
' Set a reference to the settings sheet
Set settingsSheet = ThisWorkbook.Worksheets("Sheet1") ' source
' Gather the report sheet's name
reportSheetName = settingsSheet.Range("C7").Value ' good
On Error GoTo ErrorExit
'If this doesnt match, display the message and exit sub, else continue the sub
Set reportSheet = Sheets(reportSheetName)
ErrorExit:
MsgBox "Incorrect Sheet Name or It Does Not Exist"
Exit Sub
解决方案
你可以这样做:
On Error Resume Next 'ignore errors
Set reportSheet = Sheets(reportSheetName)
On Error Goto 0 'stop ignoring errors
If reportSheet is nothing then
Msgbox "no sheet named '" & reportSheetName & "' in this workbook!"
Else
'all good
End If
推荐阅读
- python - 数字未转换为字符串
- javascript - 使用 javascript 创建一个包含 3 列的表
- azure-devops - AppCenter 上的任务发布构建工件以错误结束:操作已取消
- reactjs - Django CORS 请求仅在服务器上创建 403 Forbidden Error
- java - 如何在 jbpm 任务的数据分配 I/O 中调用 getter 方法?
- bash - 用 NOT EQUAL / OR 比较多个字符串
- php - Wordpress 如何解决 CORS 问题未定义的数组键“端口”
- java - 损坏的java swing组件
- json - 我该如何解决这个问题:/update_item 处的 JSONDecodeError 预期值:第 1 行第 1 列(字符 0)
- android - 如何在群组中添加时间戳以推送通知 - Raact Native - Android