简体   繁体   中英

VBA putting special character in string

Range("E2").Formula = "=" & column1name & "2" & "" | "" & column2name  & "2"

I am trying to make formula in VBA. I want to set E2 =( A2 | B2) . I already used function to convert column A into variable column1name already. So VBA will read it as A. but I am getting error that highlight my "|" and saying

invalid character.

How can I solve this problem?

Range("E2").Formula = "=" & column1name & "2 | " & column2name & "2"

will return

=A2 | B2

// Edit according comments

Range("E2").Formula = "=" & column1name & "2 & ""|"" & " & column2name & "2"

will output

=A2 & "|" & B2

If your intent is to join A2 and B2 cell through formula using PIPE (|) character then you can try below code.

Range("E2").Formula = "=" & column1name & "2&""|""&" & column2name & "2"

Alternative via Join()

In order not to loose a clear view over multiple quotation-mark sequences, I'd suggest to separate into tinier parts as follows:

    Const PIPE As String = """|"""         ' pipe character with quotation-marks
    Sheet1.Range("E2").Formula = _
         "=" & Join(Array(column1name & "2", PIPE, column2name & "2"), "&")

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM