【问题标题】:Using MsgBox and get error msg 1004 when I select "Cancel" - Need the macro to just end normallyUsing MsgBox and get error msg 1004 when I select \"Cancel\" - Need the macro to just end normally
【发布时间】:2022-12-15 08:03:28
【问题描述】:

First I selected "Yes" to the question "Change Worksheet Name?". Then the message "Type new Worksheet Name" appears. Instead of typing in a new name and selecting "OK", I select the "cancel" button and my error messages are displayed. How do I avoid seeing the error messages and just let the macro end "quietly"?

Option Explicit ' Force explicit variable declaration.


Sub ChangeSheetName()

Dim Carryon As String

On Error GoTo eh

Carryon = MsgBox("Change Worksheet Name?", vbYesNo)

If Carryon = vbYes Then


    Dim shName As String
    Dim currentName As String
    currentName = ActiveSheet.Name
    shName = InputBox("Type new Worksheet name")
    ThisWorkbook.Sheets(currentName).Name = shName
End If
Exit Sub

eh:
    MsgBox "The following error occured." _
        & vbCrLf & "" _
        & vbCrLf & "Error Number is: " & Err.Number _
        & vbCrLf & "" _
        & vbCrLf & "Error Description is: " & Err.Description _
        & vbCrLf & "" _
        & vbCrLf & "You likely hit the Esc key to stop renaming the Worksheet." _
        & vbCrLf & "" _
        & vbCrLf & "No worries.  You can try again to rename or leave it as is." _
        & vbCrLf & "" _
        & vbCrLf & "No harm done."

End Sub

【问题讨论】:

    标签: excel vba error-handling inputbox msgbox


    【解决方案1】:

    You've declared Carryon as a string variable - vbYes (and other messagebox results) are numeric constants. Change Dim Carryon As String to Dim Carryon As Long

    【讨论】:

      猜你喜欢
      • 2022-12-27
      • 2022-11-20
      • 2022-12-02
      • 2021-12-10
      • 2022-12-26
      • 2022-12-19
      • 2022-12-27
      • 2022-12-01
      • 2019-09-18
      相关资源
      最近更新 更多