在inputbox的cancel选项中删除对象所需的消息

时间:2015-08-03 08:28:33

标签: excel excel-vba vba

当用户按下取消按钮时,有没有办法删除从输入框中弹出的错误消息(对象所需消息)?

Sub WorkingDuoFunctionCode()

    Dim rng As Range, inp As Range

    'to remove 0 values that may be a result of a formula or direct entry.

    Set inp = Selection
    inp.Interior.ColorIndex = 37
    Set rng = Application.InputBox("Copy to", Type:=8)
    rng.Parent.Activate
    rng.Select
    inp.Copy
    Worksheets("Sheet2").Paste Link:=True

    For Each cell In Range("A1:CL9935")
       If cell.Value = "0" Then cell.Clear
    Next

End Sub

2 个答案:

答案 0 :(得分:0)

不太确定您使用输入框的原因,甚至不在代码中使用它。

这应该处理错误。

Sub WorkingDuoFunctionCode()

    Dim rng As Range, inp As Range

    'to remove 0 values that may be a result of a formula or direct entry.
    Set rng = Nothing
    Set inp = Selection
    inp.Interior.ColorIndex = 37
    On Error Resume Next
    Set rng = Application.InputBox("Copy to", Type:=8)
    On Error GoTo 0
    If TypeName(rng) <> "Range" Then
        MsgBox "Cancelled...", vbInformation
        Exit Sub
    Else
        rng.Parent.Activate
        rng.Select
        inp.Copy
        Worksheets("Sheet2").Paste Link:=True
    End If
    For Each cell In Range("A1:CL9935")
        If cell.Value = "0" Then cell.Clear
    Next
    Application.CutCopyMode = 0

End Sub

答案 1 :(得分:0)

这不是 InputBox 错误。这是你错误的用法。在您的代码中,您可以立即从 InputBox 返回值设置值。由于将空值(&#34;&#34;)设置为范围对象,可能会导致错误。

因此,您需要修改如下:

Sub WorkingDuoFunctionCode()

    Dim rng As Range, inp As Range
    Dim inputRange As String

    'to remove 0 values that may be a result of a formula or direct entry.

    Set inp = Selection

    inp.Interior.ColorIndex = 37

    inputRange = Application.InputBox("Copy to")

    If Not IsEmpty(inputRange) Then

        Set rng = Range(inputRange)

        rng.Parent.Activate
        rng.Select
        inp.Copy
        Worksheets("Sheet2").Paste Link:=True

        For Each cell In Range("A1:CL9935")
           If cell.Value = "0" Then 
               cell.Clear
           End If
        Next

    End If

End Sub

未经测试。给你的建议。如果它不起作用,请告诉我。