Paolo Bernasconi
Paolo Bernasconi

Reputation: 2030

Quotation marks in VBA

In my current VBA code, I have a query in which I am using Chr(34) to put quotation marks between some of my variables.

I was wondering what alternatives exist to this. This is a simple question, i know, but I haven't had any success with repeating quotation marks like this

" & variable string here & "

My code is messy for one and not understandable for people who are not familiar with VBA:

comboService = Chr(34) & Me.Combo8.Value & Chr(34)

Also, this hasn't worked:

comboService = """" & Me.Combo8.Value & """"

Can you perhaps tell me why?

Thanks in advance.

Upvotes: 8

Views: 99848

Answers (3)

Grady Patterson
Grady Patterson

Reputation: 71

I took a page from MS (the old vbCRLF) a while back, and just define any "tricky" characters I'll need as a string at the top of my code ...

Dim vbDblQuote As String
vbDblQuote = Chr(34)

Now you can just use that pseudo-constant as you build strings ...

strMyString = "Just another string " & vbDblQuote & "with quotes" & vbDblQuote & "!"

This makes code more readable, and also helps avoid "miscounted quote errors"

Upvotes: 7

John
John

Reputation: 1

I have found the same behavior if I output to a file using the Write command. Any double quotes get repeated.

However, if you construct the string and then output to file using the Print command, this does not happen and all works as expected.

Upvotes: 0

transistor1
transistor1

Reputation: 2925

This:

comboService = """ & Me.Combo8.Value & """

is what you posted, but you need to add an extra quotation mark in order to add a literal quotation mark:

comboService = """" & Me.Combo8.Value & """"

Double-quotes within a string are what you are looking for.

aVar = "This: "" is a literal quotation mark"

Upvotes: 13

Related Questions