insert Excel formula with VBA code

Arcadian

Board Regular
Joined
Jul 27, 2004
Messages
111
Hi all,

I have some VBA code wich inserts new rows. In one of the cells I want VBA to enter the following formula:
VBA Code:
Range.Formula = "=IF(I2="";"";G2*VLOOKUP(I2;Brongegevens!B2:C7;2))"
But somehow I get errors. I suppose it has something to do with the quotes being part of the formula, but also part of the VBA code, but I don't know all the VBA rules to do this correctly. Google told me quotes need to be in quotes too, but I must be doing it wrong :)

Also, eventually I would like the row numbers in the formula to be equal to the variable NextFree. I assume it would look something like this:

VBA Code:
"=IF(I" & NextFree & "="";"";G" & NextFree & "*VLOOKUP(I" & NextFree & ";Brongegevens!B2:C7;2))"

But again, I'm not sure of the correct syntax.

I hope someone can help me.
 

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.
Hi

When using formulas in VBA you need to include additional quotations.

Also you are missing your range at the beginning.

Range.Formula should be Range ("your range"). Formula.

VBA Code:
Range("YourRange").Formula = "=IF(I2="""","""",G2*VLOOKUP(I2,Brongegevens!B2:C7,2,FALSE))"

The below should assist.

VBA Code:
Range("YourRange").Formula = "=IF(I" & NextFree & "="""","""",G" & NextFree & "*VLOOKUP(I" & NextFree & ",Brongegevens!B2:C7,2,FALSE))"
 
Upvote 0
Solution
I did a quick test, because I have the Dutch language setting active and it turns out VBA doesn't like it if I use the Dutch translation of the formula's.
 
Upvote 0

Forum statistics

Threads
1,215,094
Messages
6,123,071
Members
449,092
Latest member
ipruravindra

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top