防御性地使用application.inputbox()

时间:2013-10-10 15:35:01

标签: excel excel-vba vba

我有以下内容:

Private Sub cmdColumnLetter_Click()
    Dim colRange As Range

    Set colRange = Excel.Application.InputBox( _
    Prompt:="Please Select Any Cell In ""Splitter"" Column", _
    Title:="Column", _
    Default:=fTableRange.Columns(1).Column, Type:=8)

    fColNumber = colRange.Column
    TxBoxColumnNum = fColNumber
End Sub

如果用户点击取消,则Set colRange =失败,因为它正在寻找将对象分配给此变量。我是否必须使用On Error结构来防止此错误或是否有更优雅的方法?

2 个答案:

答案 0 :(得分:2)

分配对象和值的不同语法是IMO,这是VBA的一个缺点。

因此,返回对象或值的InputBox函数会导致错误。

但是,传递语法的函数参数是相同的。

探索这个,我的目的和替代解决方案,实际上并不比错误处理解决方案更好:

Function SetObject(v, ByVal ExpectedTypeName As String) As Object
    If TypeName(v) = ExpectedTypeName Then Set SetObject = v
End Function

Private Sub cmdColumnLetter_Click()
    Dim colRange As Range

    Set colRange = SetObject(Excel.Application.InputBox("input", Type:=8), "Range")
    If Not colRange Is Nothing Then
        Debug.Print "..."
    End If
End Sub

SetObject接受对象或值,但如果typename与预期的匹配,则始终返回给定的对象;如果不匹配,则Nothing

答案 1 :(得分:1)

是的,你必须要OERN

Sub Test()
    Dim colRange As Range
    Dim fColNumber As Long, TxBoxColumnNum As Long

    On Error Resume Next
    Set colRange = Excel.Application.InputBox( _
    Prompt:="Please Select Any Cell In ""Splitter"" Column", _
    Title:="Column", Default:=fTableRange.Columns(1).Column, Type:=8)
    On Error GoTo 0

    If colRange Is Nothing Then Exit Sub

    fColNumber = colRange.Column
    TxBoxColumnNum = fColNumber
End Sub