大家都知道在這一點上,您可以執行如下操作,將公式應用於一個範圍,並且右側的單元格引用將動態更新: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
,但它們很慢並且想要避免它們。
'Debug.Print'您ISBLANK()公式,我想你會看到它不是你所期望的。 –
爲什麼不使用變量並使用不同的匹配結果填充它們?然後,您只需將變量插入公式中,代碼將更容易排除故障。 – teylyn