0

I want to test if a range exists to be able to create the following pattern:

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

Function exists(r as range) as boolean

End function

Here is an example of a range that I would like to test if it exists or not

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

How can I do this?

2 Answers 2

1

You could do it this way:

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

And the function:

   Function RangeExists(s As String) As Boolean
        On Error GoTo No
        RangeExists = Range(s).Count > 0
    No:
    End Function
Sign up to request clarification or add additional context in comments.

4 Comments

elegant function RangeExists
why don't you declare myRange as String directly? instead of entering a string in the inputbox, send it to myRange which is a variant and then convert it back to a string?! Uneccessairily complicated or do I miss something?
@Kathara It is because i used this code personnaly with an array and not with an Input box. That is true you can directly declare the input box as string. I did not change it because the most important was the function and not the Sub.
@manu aah, ok. Well then it's just nicer for the eye if you'd change it and it will probably be faster by 0.0000x seconds ;)
1

Avoiding the label required in ON ERROR GOTO is also possible 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.