I have looked at the other posts around errors when programmatically inserting formulas into Excel cells using VBA. But none of the tricks seem to help with the specific formula I am trying to insert. The .formula action syntax seems ok, since if I use a simple formula like "=3+3", the code executes ok. The formula I want to insert also seems ok, since when I look at it in the Immediate Window and then paste into manually into the Excel cell, it works correctly... any ideas! Here's the code:
Public Sub Populate_Formulae()
Dim oWrkBk As Workbook
Dim oWrkSht As Worksheet
Dim strLineNumber As String
Dim intCounter As Integer
Dim rngColB As Range
Dim rngColA As Range
Dim rngColD As Range
Dim strFormula As String
Dim intCellCounterLo As Integer
Dim intCellCounterHi As Integer
Set oWrkBk = Excel.ActiveWorkbook
Set oWrkSht = oWrkBk.Sheets("WerkBonApp")
intCellCounterLo = 10 'first source row to check in
intCellCounterHi = 29 'last source row to check in
For intCounter = 17 To 362 'start processing the target sheet at row 17 "LIJN C"
'Determine which row we are parsing by checking column B
Set rngColB = oWrkSht.Cells(intCounter, 2)
If InStr(1, rngColB.Text, "LIJN") <> 0 Then
strLineNumber = Right$(rngColB.Text, 1)
Else
'Put the formulae in the cells in column A
'Set Column A formula
Set rngColA = oWrkSht.Cells(intCounter, 1) 'get the current cell to populate the formula
' create the formula string
strFormula = "=VLOOKUP(MAX('Lijn " & strLineNumber & "'!I" & intCellCounterLo & ":'Lijn " & strLineNumber & "'!I" & intCellCounterHi & ");'Lijn " _
& strLineNumber & "'!I" & intCellCounterLo & ":'Lijn " & strLineNumber & "'!J" & intCellCounterHi & ";2;FALSE)"
'strFormula now equates to:
' =VLOOKUP(MAX('Lijn C'!I10:'Lijn C'!I29);'Lijn C'!I10:'Lijn C'!J29;2;FALSE)
' this works when manually entered into the Excel cell
' but gives error when executed in VBA code:
' Run-time error '1004':
' Application-defined or object-defined error
'put the formula into the current cell
rngColA.Formula = strFormula 'get error message. This function works if strFormula= "=3+3" , for example.
End If
Next intCounter
End Sub
Any and all advice very welcome!
Paul