如何从各种文件路径中的不同工作簿中检索单元格值?

时间:2016-01-14 05:03:38

标签: excel vba excel-vba

有问题的列是D,E,F,G和H,我希望它们从不同文件位置的其他工作簿中的单元格中检索值。

Index.xlsx中的每个上述列对应于我拥有的发票工作簿中的某些单元格(例如000000.xlsx,000006.xlsx和000011.xlsx)。

但是,并非所有发票都位于同一文件夹中。例如, 000000.xlsx 位于“C:\ Users \ Jimmy \ Documents \ Excel Formula Testing \ 2015 \ January”中, 000007.xlsx 位于“C:\”中用户\ Jimmy \ Documents \ Excel公式测试\ 2015 \ March“

为了澄清,这就是我希望他们做的事情。

    Index.xlsx 中的
  • D2 从000000.xlsx中 B1 检索值
  • Index.xlsx 中的
  • E2 B5 中检索值   000000.xlsx
  • Index.xlsx 中的
  • F2 从000000.xlsx中 B6 检索值
  • Index.xlsx 中的
  • G2 从000000.xlsx中 B7 检索值
  • Index.xlsx 中的
  • H2 B9 中检索值   000000.xlsx

enter image description here

*我有数百张发票,因此我无法手动输入,因此我需要一个自动执行此操作的公式。但是,是否可以在不使用VBA的情况下为此制定公式(我不知道它)?

**第三列是根据this主题中的公式创建的。

1 个答案:

答案 0 :(得分:2)

这段代码可以解决问题。

Sub test()

Dim ChkRng As Range, ws As Worksheet, strPath As String, strMonth As String, cell As Range, strSheet As String, strYear As String, strFormula as string

Set ws = ActiveSheet

strPath = "C:\Users\Jimmy\Documents\Excel Formula Testing\"

With ws
    Set ChkRng = .Range("A2", Range("A" & Cells(.Rows.Count, "A").End(xlUp).Row))
End With

For Each cell In ChkRng
    strYear = Right(cell.Value, 4) & "\"
    strMonth = Left(cell.Value, InStr(1, cell.Value, " ") - 1) & "\"
    strFile = cell.Offset(0, 1).Text & ".xlsx"
    strSheet = "Sheet1"
    strFormula = "='" & strPath & strYear & strMonth & "[" & strFile & "]" & strSheet
    cell.Offset(0, 3).Formula = strFormula & "'!B1"
    cell.Offset(0, 4).Formula = strFormula & "'!B5"
    cell.Offset(0, 5).Formula = strFormula & "'!B6"
    cell.Offset(0, 6).Formula = strFormula & "'!B7"
    cell.Offset(0, 7).Formula = strFormula & "'!B9"
Next cell

End Sub

根据需要更改静态字符串,如果文件夹和文件存在,它应该可以工作。 至少它在我的小编做的例子中为我做了。

PS。请记住将strSheet更改为发票文件中工作表的名称,如果它是静态工作表名称,请在strPath下向上移动,或至少在For Each .... Next Loop上移动。

如果它不起作用,请发表评论,我会看到我能做些什么。