简体   繁体   中英

How can I correct this “runtime error 1004 method range of object _global failed” error?

I'm trying to open a file based on a named reference in my excel work book. My code:

Sub OpenCustomerData()
    wb = ActiveWorkbook.Name

    reference = "[" & wb & "]Individual" & "!customer_id"

    customer_id = Range(reference)

    Workbooks.Open Filename:=customer_id.Value & ".csv"
End Sub

Stepping through the code, the reference looks to me to be right: [MyBook.xlsm]Individual!customer_id but I get the 1004 error when I pass that as an argument to the Range() function.

Why?

You could set the names range to a variable like so

Set CustID = ActiveWorkbook.Names("customer_id").RefersToRange
Workbooks.Open Filename:=CustID.Value & ".csv"

If you're in the active workbook anyway, then just use the sheet name and qualify the range:

Sub OpenCustomerData()
    Workbooks.Open Filename:=Sheets("Individual").Range("customer_id").Value
End Sub

If you want to use customer_id as a range (aka cell ) reference and retrieve the Range.Value property out of it in your concatenated string filename then you need to Set it.

SET customer_id = Range(reference)
Workbooks.Open Filename:=customer_id.Value & ".csv"

If you just want customer_id as the value of the range to start with then you do not need to Set it, but you use it as a variable with a stored value, not as a Range object .

customer_id = Range(reference).VALUE
Workbooks.Open Filename:=customer_id & ".csv"

Not declaring customer_id demonstrates ambiguity as to how it should be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM