0

Scenario: I have a code that should write a formula to a worksheet cells. This formula is for an API to retrieve some value. My formula is inside a loop (this is done for multiple columns) and references the first row for an identifier.

The original formula:

=FS(B1;"FI(DATE,,DATE)")

The modified formula with the floating reference (inside the loop):

For i = 1 To lColumn
    If wb.Worksheets("Dates").Cells(i, 1).Value <> "" Then
        wb.Worksheets("Dates").Cells(i,2).value = "=FS(" & i & "1;"FI(DATE,,DATE)")"
    End If
Next i

Where lColumn is some pre-defined number.

Issue: I keep getting the "Unexpected end of statement" error in the formula part of the loop.

What I already tried: I tried different variations, repositioning the "s and 's, for example:

wb.Worksheets("Dates").Cells(i,2).value = "'"=FS(" & i & "1;"FI(DATE,,DATE)")""

or

wb.Worksheets("Dates").Cells(i,2).value = "'=FS(" & i & "1;"FI(DATE,,DATE)")"

or

wb.Worksheets("Dates").Cells(i,2).value = "'""=FS(" & i & "1;"FI(DATE,,DATE)")"

and so on. But the error still persists.

Question: What is the proper way to do this operation?

DGMS89
  • 1,507
  • 6
  • 29
  • 60

2 Answers2

3

Working with formulas in VBA is a little bit tricky:

  • To write a formula, use the range.formula property, not the .value.

  • You have to write the formula as if you are using an english Excel. Parameter-separator is comma (not semicolon).

  • If a formula needs a quote, double it so that the VBA compiler understands that you want a quote within a string.
  • I find it helpfull to write a formula into a variable before assigning it - you can check in the debugger if it is exactly how it should before assigning it.
  • To check how the formula should look like, write it into a cell, change to the VBA-editor, open the immediate window and write ? activecell.formula

Try (untested as the formula you need is not valid to us):

with wb.Worksheets("Dates")
  dim f as string, adr as string
  adr = cells(i, 1).address(false, false)   ' get rid of Dollar signs
  f = "=FS(" & adr & ",""FI(DATE,,DATE)"")"
  .Cells(i, 2).formula = f
end with
FunThomas
  • 23,043
  • 3
  • 18
  • 34
1
wb.Worksheets("Dates").Cells(i,2).formula = "=FS(" & Cells(1, i).Address(0,0) & ";""FI(DATE,,DATE)"")"

There may be a better way to convert the column number to a letter (which is the problem you are having, along with the double quotes)!