插入公式与VBA到Excel中

我需要通过VBA将此公式添加到一系列行中

=WENN(ISTNV(VERWEIS(2;1/(Januar!A1:A99&"*"&Januar!B1:B99=A16&"*"&B16);Januar!D:D));" ";VERWEIS(2;1/(Januar!A1:A99&"*"&Januar!B1:B99=A16&"*"&B16);Januar!D:D)) 

它的德语,但唯一重要的是,我需要用循环variablesreplace16

 For i = 17 To Rows.Count Cells(14, i).FormulaLocal = "=WENN(ISTNV(VERWEIS(2;1/(Januar!A1:A99&"*"&Januar!B1:B99=A"&i"&""*""&B""&i"");Januar!D:D));"" "";VERWEIS(2;1/(Januar!A1:A99&""*""&Januar!B1:B99=A""i""&""*""&B""i"");Januar!D:D))" Next 

我读了一些文章,但我似乎并没有工作:/

公式string是一个用双引号括起来的string&我们可以使用&将variables连接到该string中&如果我们通过复制来转义它们,我们可以在string中加双引号。

例子:

 Dim s as String Dim i as Integer i = 123 s = "Test " & i & " Test" s = "Test """ & i & """ Test" 

在你的特殊情况下,额外的困难是你不仅在VBA而且在公式string中还有&作为连接操作符。 这导致混乱。 我build议在stringvariables中首先创build公式string。 所以你可以Debug.print这个string并检查。

 For i = 17 To Rows.Count sFormula = "=WENN(ISTNV(VERWEIS(2;1/(Januar!A1:A99&""*""&Januar!B1:B99=A" & i & "&""*""&B" & i & ");Januar!D:D));"" "";VERWEIS(2;1/(Januar!A1:A99&""*""&Januar!B1:B99=A" & i & "&""*""&B" & i & ");Januar!D:D))" Debug.Print sFormula Cells(i, 14).FormulaLocal = sFormula Next 

顺便说一句:在Cells ,第一个参数是行索引,第二个参数是列索引。 所以根据你的代码( i是行号)应该是Cells(i, 14)

顺便说一句:我build议不要使用FormulaLocalFormula和英文函数名称和英文公式符号(逗号作为参数分隔符而不是分号)。 这将是更多的区域独立。

阿克塞尔给你解决scheme

build立它你可能想要采用FomulaLocalR1C1属性来简化你的公式:

例如:

 =A" & i & "&""*""&B" & i 

会成为:

 "=RC1 & ""*"" & RC2" 

要么

 "=VERKETTEN(RC1;""*"";RC2)" 

在这种情况下,您必须将所有范围引用转换为R1C1表示法,以便:

 Januar!A1:A99 Januar!B1:B99 

成为:

 Januar!R1C1:R99C1 Januar!R1C2:R99C2