Assigning a String to a Variable in Word 2003

A

Alan Stancliff

In Word 2003 VBA, if I wanted to assign a string to a variable, I could
do it with the following code:

Sub eraseme()
Dim MyText As String
MyText = "Here is my wonderful string, assigned to its very own variable"
MsgBox MyText
End Sub

But supposing the string I wanted to assign to a variable was this?
Here is my "wonderful" string, assigned to (its very own) variable. 'I
hope.
And it had all those things that mean something special in VBA, such as
quotation marks, parentheses, apostrophes? What would be the correct
approach to that?

Regards,

Alan Stancliff
 
J

Jay Freedman

In Word 2003 VBA, if I wanted to assign a string to a variable, I could
do it with the following code:

Sub eraseme()
Dim MyText As String
MyText = "Here is my wonderful string, assigned to its very own variable"
MsgBox MyText
End Sub

But supposing the string I wanted to assign to a variable was this?
Here is my "wonderful" string, assigned to (its very own) variable. 'I
hope.
And it had all those things that mean something special in VBA, such as
quotation marks, parentheses, apostrophes? What would be the correct
approach to that?

Regards,

Alan Stancliff

Hi Alan,

The only character you need to be concerned with is the double quote, because
that's the marker for the beginning and end of a string literal. All the other
characters can be plunked into the literal just as they are.

There are a couple of ways to deal with double quotes:

- You can type the double quote twice where it should be embedded in the string:

MyText = "Here is my ""wonderful"" string with (parentheses)."

- You can declare a constant whose value is a double quote character, and
concatenate that into the string where needed:

Const qt = """"
MyText = "Here is my " & qt & "wonderful" & qt & " string."

- You can use the Chr(34) function, where 34 is the ASCII value of the double
quote character. Personally, I think this is too distracting when reading code.

MyText = "Here is my " & Chr(34) & "wonderful" & _
Chr(34) & " string with (parentheses)."
 
A

Alan Stancliff

Hi Jay and Greg,

Thanks for the information and the help.

Regards,

Alan Stancliff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top