繁体   English   中英

用VBA将公式插入Excel

[英]insert formula with vba into 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)) 

它的德语,但唯一重要的是,我需要用循环变量i替换16

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

我读了一些文章,但我似乎没有用:/

公式字符串是用双引号"括起来的字符串文字。我们可以使用&将变量连接到该字符串中。如果通过重复转义转义,我们可以在字符串中使用双引号。

例子:

Dim s as String
Dim i as Integer
i = 123

s = "Test " & i & " Test"

s = "Test """ & i & """ Test" 

在您的特殊情况下,额外的困难是您不仅在VBA具有&作为串联运算符,而且在公式字符串中也具有。 这导致混乱。 我建议首先在字符串变量中创建公式字符串。 因此,您可以Debug.print此字符串并检查。

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)

顺便说一句:我建议不要使用FormulaLocal而是使用Formula和英语函数名称以及英语公式表示法(逗号作为参数定界符,而不是分号)。 这将与语言环境无关。

Axel给您解决方案

在此基础上,您可能希望采用FomulaLocalR1C1属性来简化公式:

例如:

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

会成为:

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

要么

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

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

Januar!A1:A99

Januar!B1:B99

成为:

Januar!R1C1:R99C1
Januar!R1C2:R99C2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM