I'm trying to set a formula using a macro. I've come to a point where my macro creates a string with formula that I want to insert but I get an error when I try to set the formula. Here's the code:
Option Explicit
Function AutoFormula(blocks As Range, target As Range)
Dim blockedArr() As String
Dim cellValue As String
Dim ret As String
Dim i As Integer
'sprawdzenie zakresu
If (blocks.Cells.Count > 1) Then
AutoFormula = "Tylko 1 komórka jako parametr!"
Exit Function
End If
'wczytanie komorki
cellValue = blocks.Cells(1, 1).Value
'split
blockedArr = Split(cellValue, ",")
ret = "=WYSZUKAJ.PIONOWO(E7;$E$2:$G$5;3;FAŁSZ)"
For i = LBound(blockedArr, 1) To UBound(blockedArr, 1)
ret = ret + "+SUMA.JEŻELI(A7:A1000;" + blockedArr(i) + ";G7:G1000)"
Next i
target.Cells(1, 1).Value = ret
End Function
Sub auto()
Call AutoFormula(Worksheets("reorganizacja").Range("D7"), Worksheets("reorganizacja").Range("G7"))
End Sub
I get a
Runtime error 1004: Application-defined or object-defined error
in the last line of AutoFormula function. I have no idea what's that supposed to mean except that 'there is some error related to something'. Anyways, I also tried using target.Formula = ret
but it's the same case.
When you fill a cell with .formula
using VBA you have to use the English version of the functions you use. So WYSZUKAJ.PIONOWO is VLOOKUP
and SUMA.JEŻELI is SUMIF
(according to Google translate). Oh and FAŁSZ is probably False
.
Scott's comment is the proper solution - using FormulaLocal. However, now having read about differences with Formula and FormulaLocal, I don't understand why Formula wouldn't work with english versions of the excel functions...
Anyways got it to work, thank you Scott!
The error message is not very descriptive (when are they right?), it basically means there is a SYNTAX ERROR in your formula. In your case it may have to do with your local.
I suggest simplifying the formula then adding complexity to help reveal where the problem is. Or if it's a local issue you can try using .FomulaLocal as Scott Craner suggested.
Another good idea is to MsgBox your string variable that holds the formula; this will make it easier to see what the formula looks like after doing string concatenations.
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.