如果范围存在,则为文本Excel VBA

时间:2016-01-28 08:33:39

标签: excel vba excel-vba

我想测试一个范围是否能够创建以下模式:

if not exists(r) then
   MsgBox("Range is missing")
end if

Function exists(r as range) as boolean

End function

以下是我想测试的范围示例(如果存在或不存在)

Call RangeExists(lob.ListColumns("Leverera utt").DataBodyRange)

我该怎么做?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

Sub CheckRange()

    Dim myRange As Variant

    myRange = InputBox("Enter your name of your range")

           If RangeExists(CStr(myRange)) Then
                MsgBox "True"
           Else
                MsgBox "No"
           End If

    End Sub

功能:

   Function RangeExists(s As String) As Boolean
        On Error GoTo No
        RangeExists = Range(s).Count > 0
    No:
    End Function

答案 1 :(得分:1)

也可以避免ON ERROR GOTO中要求的标签 Function RangeExists(rngName As String) As Boolean On Error Resume Next RangeExists = Range(rngName).Column And (Err.Number = 0) Debug.Print "RangeExists= " & RangeExists & " " & rngName End Function