Formula is giving error when I add “text”

跟風遠走 提交于 2019-12-11 04:59:45

问题


I'm trying to write a Macro that will do the formatting of a report. All is well up until I try to create the transaction reference number.

The formula basically goes =A2 & "-" & B2 & "ABCD"

When I insert this into my macro it becomes

Range("C2").Formula = "=A2 & "-" & B2 & "ABCD""

As soon as I add my hyphen or the letters at the end it gives me "Compile Error: Expected: end of statement"

What am I doing wrong?

Edit: So the output would be contentOfA2-contentOfB2 ABCD


回答1:


Try this. When adding quotes inside a string, double up the quotes so the program knows you aren't simply ending the string.

Range("c2").Formula = "=A2 & ""-"" & B2 & ""ABCD"""

Example..

Range("A1").value = "adding a quote inside a string ""so and so said something"" is like this."

output: adding a quote inside a string "so and so said something" is like this.




回答2:


Try to do it reversed - e.g. write the formula in excel like this:

Then select the formula and write the following in the VBA:

Public Sub TestMe()

    Debug.Print Selection.Formula

End Sub

On the direct window you would have this: =A2&"-"&B2&"abcd" This input should be edited a bit, because it comes from the console and you need to escape the ". Like this: "=A2 & ""-"" & B2 & ""abcd"""

You can elaborate further, by writing Debug.Print Selection.FormulaR1C1, if you need it.

At the end, you can use something like this, to escape the counting of the parenthesis. It would work ok:

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

It changes the single quote to a double and then it puts the formula in a quote. In my code, it is code strParenth.



来源:https://stackoverflow.com/questions/43050331/formula-is-giving-error-when-i-add-text

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