VBA:在Range.Formula右侧的位置使用数组索引

soc*_*pet 0 excel vba excel-vba

此时所有人都知道您可以执行以下操作将公式应用于范围,右侧的单元格引用将动态更新:

Range("A1:A10").Formula = "=J2+M2"
Run Code Online (Sandbox Code Playgroud)

这不是我要问的.我试图将数组索引传递到a的右侧Range.Formula,我没有得到我想要的结果.首先,这是我的代码,左侧工作正常(请注意,这xl.是由于这是从MS Access启动):

' Get the new amount of columns since new ones have been added
lastColumn = xl.Cells(1, xl.Columns.Count).End(xlToLeft).Column

' Create and array of the header names to quickly locate column number
cols = xl.Range(xl.Cells(1, 1), xl.Cells(1, lastColumn)).Value

' Apply the formulas
xl.Range(xl.Cells(2, xl.Match("FCode", cols, 0)), xl.Cells(lastRow, xl.Match("FCode", cols, 0))).Formula = 
Run Code Online (Sandbox Code Playgroud)

这很适用于正确的范围.如果我把"ASD","=J2+M2"在右侧,它更新了正确的范围内.当我需要xl.Match(...)在右侧使用作为公式的一部分时,问题就出现了.

例如:

"=ISBLANK(" & xl.Range(xl.Cells(2, xl.Match("NCode", cols, 0)), xl.Cells(2, xl.Match("NCode", cols, 0))) & ")"
Run Code Online (Sandbox Code Playgroud)

返回一个1004: Application-defined or object-defined error.这应返回=ISBLANK(K2),=ISBLANK(K3),etc.在应用范围.

只是简单的引用应该等于=K2,=K3,etc最终相当于是在单元格的值K2.例如,=14它适用于整个范围.在它甚至不会返回值K3,K4,etc.这是用于此的公式:

"=" & xl.Range(xl.Cells(2, xl.Match("PCode", cols, 0)), xl.Cells(2, xl.Match("PCode", cols, 0)))
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?这样做的原因是因为列我需要引用报告之间的更改,但标题名称保持不变.它可以是一个报告中的列M,但是另一个报告中的列Z. 到目前为止我一直在使用For Loops,但它们很慢并且想要避免它们.

Tim*_*ams 6

"=ISBLANK(" & xl.Range(xl.Cells(2, xl.Match("NCode", cols, 0)), _
                       xl.Cells(2, xl.Match("NCode", cols, 0))) & ")"
Run Code Online (Sandbox Code Playgroud)

应该是

"=ISBLANK(" & xl.Cells(2, xl.Match("NCode", cols, 0)).Address(false, false) & ")"
Run Code Online (Sandbox Code Playgroud)