0

In VBA I am trying to store a named range into a variable then pass it to a function but I get an error "Object doesn't support this property or method"

Function BOM(val, rng)
Dim CR_Path As String
Application.ScreenUpdating = False
CR_Path = ThisWorkbook.Sheets("Request").Cells(val, 1).Value 'Copy that path from a cell
Set mybook = Workbooks.Open(CR_Path)


mybook.Sheets("BOM").Range("A4:G28").Value = ThisWorkbook.Sheets("BOM").Range("rng").Value
mybook.Close SaveChanges:=True
Application.ScreenUpdating = True
End Function

Sub test()
Dim rng As Variant
Dim val as Integer
rng = ThisWorkbook.Sheets("BOM").Range("myTable").RefersToRange.Value
val = 2
Call BOM(3, rng)
End Sub

1 Answer 1

1

RefersToRange is a property of a Name object, not a Range.

Change

ThisWorkbook.Sheets("BOM").Range("myTable").RefersToRange.Value

To

ThisWorkbook.Sheets("BOM").Range("myTable").Value

Or

ThisWorkbook.Names("myTable").RefersToRange.Value

Other than refering to a Named range, there are more issues in your code too

Your code, refactored

'Your are not returning anything, so use a Sub
'Define your parameter types
Sub BOM(PathRow As Long, rng As Range)
    Dim CR_Path As String
    Application.ScreenUpdating = False
    CR_Path = ThisWorkbook.Sheets("Request").Cells(PathRow, 1).Value 'Copy that path from a cell
    Set mybook = Workbooks.Open(CR_Path)
    
' Use the range variable Values property
    mybook.Sheets("BOM").Range("A4:G28").Value = rng.Value
    mybook.Close SaveChanges:=True
    Application.ScreenUpdating = True
End Sub

Sub test()
    Dim rng As Range
    Dim PathRow As Long ' use meaningful names for variables
    Set rng = ThisWorkbook.Names("myTable").RefersToRange
    PathRow = 2

    ' use the variable you defined
    BOM PathRow, rng
End Sub
Sign up to request clarification or add additional context in comments.

3 Comments

Tried that and got: Runtime Error 1004 “Application-defined or Object-defined error” when Selecting Range. The issue was inside the function. ```mybook.Sheets("BOM").Range("A4:G28").Value = ThisWorkbook.Sheets("BOM").Range("rng").Value
That's not what I suggested.
This works great. Is it also possible to copy everything in that range, not just the values?

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.