【发布时间】:2017-07-18 20:58:02
【问题描述】:
我有以下代码,但它并没有到达我想要的地方:
Public Sub populateFile()
Dim wbk As Workbook
Dim fileName As String
Dim path As String
Dim pulledFormula As String
Dim pulledPath As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
path = "C:\Users\Bob\Desktop\Source Files\"
fileName = Dir(path & "*.xlsx*")
Do While fileName <> ""
Set wbk = Workbooks.Open(path & fileName, UpdateLinks:=False)
j = 24
For i = 8 To 16
With Workbooks("MasterFile.xlsm").Sheets("Sheet1")
If Application.WorksheetFunction.CountA(Workbooks(fileName).Sheets("SummaryTab").Range(Cells(i - 1, j - 21), Cells(i - 1, j - 13))) > 0 Then
.Cells(i, j - 10).Value = fileName & vbNewLine & .Cells(i, j - 10).Value
For j = 15 To 23
pulledFormula = "+" & Application.WorksheetFunction.Index(Workbooks(fileName).Sheets("SummaryTab").Range("C6:K164"), _
Application.WorksheetFunction.Match(.Cells(i, 1), Workbooks(fileName).Sheets("SummaryTab").Range("A6:A164"), 0), _
Application.WorksheetFunction.Match(.Cells(6, j), Workbooks(fileName).Sheets("SummaryTab").Range("C5:K5"), 0)).Address(External:=True)
.Cells(i, j).Value = pulledFormula & .Cells(i, j).Formula
Next j
End If
End With
Next i
wbk.Close
fileName = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
所以我试图从目录中的一堆文件中提取相关(基于索引/匹配)单元格地址。下一步是迭代地将地址与 + 号一起添加,希望最终主电子表格可以将所有打开文件中的所有相关单元格的总和放在一个单元格中(并为一堆细胞也是如此)。确切的问题是 Excel 拒绝评估生成的连接公式。非常感谢有关如何改进此代码的任何想法!
谢谢!
注意:我需要将单元格地址保留在主文件单元格中,以便其他人可以将这些地址跟踪到馈线文件,因此我不能使用评估公式。
【问题讨论】:
-
.Address(External:=True)不是Application.WorksheetFunction.Index()的函数,这不是正确的轨道。您在 VBA 中,请使用 VBA。可以使用 match 返回正确的行和列,然后使用Cells(row,column).Address(External:=True)返回正确的地址。不需要索引。 -
@ScottCraner 我同意你的方式是一种更优雅的代码编写方式。我按照你说的重写了它,但它仍然没有给我想要的东西。在这两种情况下,我都可以将输出拉到看起来像这样的单元格中 +'[File1.xlsx]SummaryTab'!$E$8+'[File2.xlsx]SummaryTab'!$E$8 我希望 Excel 向我展示数字是这两个引用的总和,但 excel 只是将其保留为如上所示。如果我进入单元格然后按 Enter,Excel 会评估公式以获取数字。理想情况下,我无需手动编辑/输入单元格就可以做到这一点。谢谢!
标签: vba excel loops concatenation