VBA Run-Time Error 9 When Sheet Name Does Not Match the Target Sheet Name

╄→гoц情女王★ 提交于 2020-04-30 06:42:05

问题


I have the following code which converts Excel Sheets with a specific sheet names into PDF and then it loops in the folder. The User can input the sheet name into the tool for the code to loop for. However, if the sheet name is incorrect or does not exist, it shows Run-Time Error 9: Subscript out of Range. Instead of this error, I would like to get a MsgBox then Exit the Sub. I tried using On Error GoTo approach, which works when the code doesnt match the sheet name to the reference cell and shows the appropriate message. However, when the correct sheet name is inserted, it shows that message and does not proceed with the code as well.

How can I fix this so I'll only get the message when the code does not find the sheet name, and in case it does, it completes the code?

This is where I'm facing the issue

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

回答1:


You can do it like this:

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


来源:https://stackoverflow.com/questions/60332267/vba-run-time-error-9-when-sheet-name-does-not-match-the-target-sheet-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!