Getting a range from a closed workbook into an array

后端 未结 2 1404
梦如初夏
梦如初夏 2021-01-07 09:16

How do I get a range of data from a closed workbook into an array in VBA? Preferably without opening the workbook.

Thanks

2条回答
  •  滥情空心
    2021-01-07 09:43

    Not sure if you can do it without opening the workbook. I built a function like below.

    Private Function GetValue(path, file, sheet, ref)
    Dim wb As Workbook
    Application.ScreenUpdating = False
    Set wb = Workbooks.Open(path & Application.PathSeparator & file)
    Worksheets(sheet).Activate
    GetValue = Range(ref)
    wb.Close savechanges:=False
    Application.ScreenUpdating = True
    End Function
    

    Then use it like

    Dim path As String
    Dim file As String
    Dim sht As String
    Dim rng As String
    path = ThisWorkbook.path
    file = "book.XLSX"
    sht = "Sheet1"
    rng = "A1:D300"
    
    ActiveSheet.Range("A1:D300").Value = GetValue(path, file, sht, rng) 
    

提交回复
热议问题