当使用VBA以编程方式将公式插入Excel单元格时,我查看了有关错误的其他文章。但是,这些技巧似乎都无法帮助我尝试插入的特定公式。 .formula动作语法似乎还可以,因为如果我使用“ = 3 + 3”之类的简单公式,则代码可以正常执行。我想插入的公式似乎也没问题,因为当我在“即时窗口”中查看该公式,然后手动将其粘贴到Excel单元格中时,它可以正常工作……任何想法!这是代码:
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
任何人和所有建议都非常欢迎!
保罗
答案 0 :(得分:0)
当尝试使用VBA将复杂公式插入Excel单元格时,您需要使用.FormulaLocal
属性。