【发布时间】:2020-12-10 22:17:09
【问题描述】:
我正在尝试将数组公式添加到工作表的表格列中。我正在使用索引匹配并拆分公式,因为所有文件名都变得非常大。我通过拆分它在代码的其他部分使用它并且它可以工作(但使用不同的引用等)。
当我尝试将匹配公式替换/插入索引公式时,我不断收到错误“类型不匹配”。当我手动执行(通过复制变量字符串值)时,它可以工作......
ATPFile = Dir(DataPath & "\*ATP*COMBINED.xls*")
ATPFileF = DataPath & "\" & ATPFile
Set wb = Workbooks.Open(ATPFileF)
'Add ATP data from ATP raw data file
sheetname = Worksheets("ATP").Name
'Get last row with data in ATP file
Dim rowCountSource As Integer
Dim ATPRowRange As Range
Dim sFomrula2 As String
With wb.Worksheets("ATP")
rowCountSource = .Cells(.Rows.Count, 2).End(xlUp).Row
End With
ref = DataPath & "\[" & ATPFile & "]" & sheetname
sFormula = "=INDEX('" & ref & "'!$P$1:$P$" & rowCountSource & ",""X_X_X"",1)"
sFormula2 = "MATCH([@Article]&[@Site],('" & ref & "'!$B$1:$B$" & rowCountSource & ")&('" & ref & "'!$D$1:$D$" & rowCountSource & "),0)"
'Add ATP info
With ws.ListObjects("Table_DCvenSDCdata")
With .ListColumns("ATP").DataBodyRange
.NumberFormat = "General"
With .Cells(1, 1)
.FormulaArray = sFormula
.Replace """X_X_X""", sFormula2
End With
.FillDown
.Value = .Value
End With
End With
.Replace """X_X_X""", sFormula2处弹出错误
文件引用和名称都是正确的。我不确定我的匹配公式中的问题出在哪里......
sFormula 字符串是这样的:
=INDEX('C:\_Store\10.05.2020\[T MA0 ATP 18.08.2020.xls COMBINED.xls]ATP'!$P$1:$P$126,"X_X_X",1)
这就是替换索引公式中“X_X_X”的 sFormula2 字符串:
MATCH([@Article]&[@Site],('C:\_Store\10.05.2020\[T MA0 ATP 18.08.2020.xls COMBINED.xls]ATP'!$B$1:$B$126)&('C:\_Store\10.05.2020\[T MA0 ATP 18.08.2020.xls COMBINED.xls]ATP'!$D$1:$D$126),0)
任何建议将不胜感激!
【问题讨论】:
-
公式必须在每一步解析。将
""X_X_X""替换为0,然后替换它。 -
然后看这里:stackoverflow.com/questions/42492758/… 看看你是否可以重做你的公式而不是数组公式。
-
Cells(1.1).Replace将替换 Cells(1,1) 值中的内容,它不会像您在此处所做的那样编辑公式。尝试将sFormula2的行放在sFormula之前,然后替换sFormula = "=INDEX('" & ref & "'!$P$1:$P$" & rowCountSource & ",""X_X_X"",1)"尝试sFormula = "=INDEX('" & ref & "'!$P$1:$P$" & rowCountSource & ", sFormula2 ,1)" -
之后从
with block中删除或注释掉.Replace """X_X_X""", sFormula2。 -
@Puntal 问题在于
.FormulaArray有 255 个字符的限制,作为一种解决方法,必须分多个步骤完成才能输入更长的字符。
标签: excel vba array-formulas type-mismatch