VBA:在范围的右侧使用位置数组索引位置。公式

问题描述:

大家都知道在这一点上,您可以执行如下操作,将公式应用于一个范围,并且右侧的单元格引用将动态更新:VBA:在范围的右侧使用位置数组索引位置。公式

Range("A1:A10").Formula = "=J2+M2" 

这不是我所问的。我试图将数组索引传递到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 = 

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

例如:

"=ISBLANK(" & xl.Range(xl.Cells(2, xl.Match("NCode", cols, 0)), xl.Cells(2, xl.Match("NCode", cols, 0))) & ")" 

返回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))) 

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

+0

'Debug.Print'您ISBLANK()公式,我想你会看到它不是你所期望的。 –

+0

为什么不使用变量并使用不同的匹配结果填充它们?然后,您只需将变量插入公式中,代码将更容易排除故障。 – teylyn

"=ISBLANK(" & xl.Range(xl.Cells(2, xl.Match("NCode", cols, 0)), _ 
         xl.Cells(2, xl.Match("NCode", cols, 0))) & ")" 

大概应该是

"=ISBLANK(" & xl.Cells(2, xl.Match("NCode", cols, 0)).Address(false, false) & ")" 
+2

你那壮丽的男人。 – sockpuppet

+0

蒂姆刚刚取得了更多的进展“壮丽的人”徽章! – Rodger