简体   繁体   中英

insert formula with vba into excel

I need to add this formula into a range of rows via 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

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. 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.

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. So according to your code ( i is the row number) it should be 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). This will be more locale independent.

Axel gave you the solution

building on it you may want to adopt FomulaLocalR1C1 property to simplify your formula:

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:

Januar!A1:A99

Januar!B1:B99

become:

Januar!R1C1:R99C1
Januar!R1C2:R99C2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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