1

I'm brand new to VBA and trying to learn variables. I have a simple piece of code that should set a variable to a range:

Sub Test()
    Dim DataRange As Range
    DataRange = Workbooks("Rooms.csv").Sheets(1).Range("A3", "AK17068")
End Sub

When I run I get Run-time error '91': Object variable or With block variable not set which.... isn't that what I did with the Dim statement? What is this referring to?

I saw in the MS docs that in certain cases (I don't fully understand when) I should use Option Strict On but when I try to use this I get a syntax error (Expected: Base or Compare or Explicit or Private). I think I am fundamentally misunderstanding how this should work (am C++ dev by training)

3 Answers 3

8

Here:

Sub Test()
    Dim DataRange As Range
    Set DataRange = Workbooks("Rooms.csv").Sheets(1).Range("A3", "AK17068")
End Sub

ObjectVariables are Set with Set

Sign up to request clarification or add additional context in comments.

Comments

4

You need to set the data range

Set DataRange = Workbooks("Rooms.csv").Sheets(1).Range("A3", "AK17068")

Comments

1

Using With Statement referring to the workbook & worksheet we are getting the advantage of not repeating workbook & worksheet names if you are planning to set more ranges. See below:

Option Explicit

Sub Test()

    Dim DataRange As Range, DataRange2 As Range

    With Workbooks("Rooms.csv").Worksheets("Sheet1") '<- Using *With Statement* referring to the workbook & worksheet
        Set DataRange = .Range("A3", "AK17068")
        Set DataRange2 = .Range("A1") '<- For example purpoces
    End With

End Sub 

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.