Apply formula in VBA?

三世轮回 提交于 2020-01-23 19:47:47

问题


I am trying to apply a formula that writes YES or NO in a cell checking if another cell starts with Q) text.

Writing it manually in Excel is working.

=IF(LEFT(A2;2)="Q)";"YES";"NO")

But when I try to do it automatically inside a macro

Range("R2").Formula = "=IF(LEFT(A2;2)=""Q)"";""YES"";""NO"")"

Run-time error '1004': Application-defined or object-defined error

Also, I will want to do it for the whole column, something like this

Range("R2:R" & lastRow).Formula = "=IF(LEFT(A2;2)=""Q)"";""YES"";""NO"")"

But for that I have to solve the first problem before.

What am I doing wrong?


回答1:


VBA uses the comma separator, irrespective of your local settings

Range("R2:R" & lastRow).Formula = "=IF(LEFT(A2,2)=""Q)"",""YES"",""NO"")"



回答2:


You could always try the record macro option: 1. Start recording 2. Paste the formula into a cell 3. Stop recording 4. Look at the recorded macro and how it formats the formula




回答3:


In general, try the following:

  • Make a workable formula in Excel

  • Then select the cell with the workable formula

  • Run the code

  • In the immediate window something useful should be printed.


The code:

Public Sub PrintMeUsefulFormula()
    Dim strFormula  As String
    Dim strParenth  As String

    strParenth = """"

    strFormula = Selection.Formula
    strFormula = Replace(strFormula, """", """""")

    strFormula = strParenth & strFormula & strParenth
    Debug.Print strFormula
End Sub

Source: Error with IF/OR in VBA




回答4:


The Range.Formula is expecting a EN-US syntax.

Use Range.FormulaLocal to insert a formula based on your regional settings:

Range("R2").FormulaLocal = "=IF(LEFT(A2;2)=""Q)"";""YES"";""NO"")"



回答5:


Instead of double double-quotes. try skipping the double quotes with .

For example: instead of ""Q"" try \"Q\"



来源:https://stackoverflow.com/questions/45463062/apply-formula-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!