简体   繁体   English

用VBA将公式插入Excel

[英]insert formula with vba into excel

I need to add this formula into a range of rows via VBA 我需要通过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)) 

its german, but the only thing that matters, is that i need to replace the 16 with the loop variable i 它的德语,但唯一重要的是,我需要用循环变量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

I read some articles but i doesnt seem to work :/ 我读了一些文章,但我似乎没有用:/

The formula string is a string literal enclosed in double quotes " . We can concatenate variables into that string using & . We can have double quotes within the string if we do escaping them by duplicating. 公式字符串是用双引号"括起来的字符串文字。我们可以使用&将变量连接到该字符串中。如果通过重复转义转义,我们可以在字符串中使用双引号。

Examples: 例子:

Dim s as String
Dim i as Integer
i = 123

s = "Test " & i & " Test"

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

In your special case the additional difficulty is that you have not only & as the concatenating operator in VBA but also within the formula string. 在您的特殊情况下,额外的困难是您不仅在VBA具有&作为串联运算符,而且在公式字符串中也具有。 This leads to confusion. 这导致混乱。 I recommend to create the formula string first within a string variable. 我建议首先在字符串变量中创建公式字符串。 So you can Debug.print this string and check. 因此,您可以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

Btw.: Within Cells the first parameter is the row index and the second parameter is the column index. 顺便说一句:在Cells ,第一个参数是行索引,第二个参数是列索引。 So according to your code ( i is the row number) it should be Cells(i, 14) . 因此,根据您的代码( i是行号),它应该是Cells(i, 14)

Btw.: I recommend not to use FormulaLocal but Formula and the English function names and English formula notation (comma as the parameter delimiter instead of semicolon). 顺便说一句:我建议不要使用FormulaLocal而是使用Formula和英语函数名称以及英语公式表示法(逗号作为参数定界符,而不是分号)。 This will be more locale independent. 这将与语言环境无关。

Axel gave you the solution Axel给您解决方案

building on it you may want to adopt FomulaLocalR1C1 property to simplify your formula: 在此基础上,您可能希望采用FomulaLocalR1C1属性来简化公式:

for instance: 例如:

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

would become: 会成为:

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

or 要么

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

in such a scenario you'd have to turn all range references to R1C1 notation so that: 在这种情况下,您必须将所有范围引用都转换为R1C1表示法,以便:

Januar!A1:A99

Januar!B1:B99

become: 成为:

Januar!R1C1:R99C1
Januar!R1C2:R99C2

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

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