简体   繁体   中英

Workbook.Open based on filepath contained in ThisWorkbook

when I step through my code (below), it gives me the following error notice:

'Run-time error '1004':

Application-defined or object-defined error

Set MEF_ITD = Workbooks.Open(Workbook.Worksheets("Dashboard").Range("F39").Value)

Set myRangeITD = ActiveWorkbook.Worksheets("Summary").Range("A915:AJ1033")

I substituted "Workbook" with this "ThisWorkbook" on the first line thinking it might be a qualifier issue, however, I received the same error notice. I am trying to open up a separate workbook whose filepath is contained in cell F39 of ThisWorkbook. The second line is attempting to define the range based on the ActiveWorkbook.

Is anyone aware of a potential solution here? Thank you!

Except of the missing ThisWorkbook your code looks ok.

BUT: as we don't know your data (eg does file really exist, does sheet exist) it is hard to tell you the reason for the error.

I would suppose to have a generic function that takes workbook-fullname, worksheets name and range-adress - does the necessary validations (file exists, sheet exists) and returns the range you are looking for.

Public Function getRangeFromWorkbook(wbSourceFullfilename As String, _
    wsSourceSheetName As String, _
    rgSourceAddress As String) As Range

On Error GoTo err_getRangeFromWorkbook

If Dir(wbSourceFullfilename, vbNormal) = vbNullString Then
    err.Raise vbObjectError, , wbSourceFullfilename & " not found."
End If

Dim wbSource As Workbook
Set wbSource = Workbooks.Open(wbSourceFullfilename)


If Not wbSource Is Nothing Then
    
    Dim wsSource As Worksheet
    On Error Resume Next    'an error is thrown if worksheet doesn't exist - this is the only error that can happen.
    Set wsSource = wbSource.Worksheets(wsSourceSheetName)
    If err <> 0 Then
        err.Raise vbObjectError, , "Sheet " & wsSourceSheetName & " not found in workbook " & wbSource.Name
    End If
    On Error GoTo err_getRangeFromWorkbook

    Dim rgSource As Range
    Set rgSource = wbSource.Worksheets(wsSourceSheetName).Range(rgSourceAddress)
End If

Set getRangeFromWorkbook = rgSource

exit_getRangeFromWorkbook:
    Exit Function
    
err_getRangeFromWorkbook:
    MsgBox err.Description, vbCritical, "get range from  workbook"
    Resume exit_getRangeFromWorkbook
    
End Function

You can then call this function like this:

Public Sub testGetRange()

Dim rgITD As Range
Set rgITD = getRangeFromWorkbook( _
    ThisWorkbook.Worksheets("Dashboard").Range("F39").value, _
    "Summary", "A915:AJ1033")
     
End Sub

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