Refer to Excel workbook by path, based on cell value data

前端 未结 3 1589
旧巷少年郎
旧巷少年郎 2021-01-06 02:15

I have an Excel sheet that draws data from other, closed Excel workbooks. Currently it works fine when I list out the closed workbook\'s entire path, but I\'d like to use a

3条回答
  •  悲哀的现实
    2021-01-06 02:57

    I think what you what to do is to find the specific record in the specific file (date named). You may do it by a simple VBA code.

    Suppose you are going to search for a record# say REC001 in A1, date file 12.10.12 at cell C1, and have the result to be display at cell A7

    On the worksheet you want to enter input and get output, rightclick the sheet tab and select 'View code' and paste the following code:

    Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Range("C1")) Is Nothing Then Exit Sub
    Range("A7").Formula = "=INDEX('C:\TEMP\[workbook" & Range("C5").Value & ".xls]SHEET1'!$B$1:$B$5, MATCH(" & Range("A1").Value & ", 'C:\TEMP\[workbook" & Range("C5").Value & ".xls]SHEET1'!$A$1:$A$5, 0))"
    End Sub
    

    Then every time you edit C1, the formula will be updated.

    Actually I don't think you should use INDEX function in your case. It is more simple to use a VLOOKUP. E.g.:

    Range("A8").Formula = "=vlookup(" & Range("A1").Value & ",'C:\TEMP\[workbook" & Range("C5").Value & ".xls]SHEET1'!$A$1:$B$5,2,false)"
    

    You will have to note on a few points: 1. you paste the code on the Sheet1 object (or the sheet name) but not to insert a new module 2. your path and filename for the target file is correct, including the .xls and .xlsx 3. your original file only cover to $B$5 4. on VBA, recommend you to save the file as .xlsm format

提交回复
热议问题