Alex
Alex

Reputation: 283

Difference between line separation "& _" and " _" in Access - VB

I can't seem to find anything specific on this. I know that in order to split up a piece of code over multiple lines, you simply add " _" to the end of the line.

However, I've noticed that some of my lines of code only work when I use "& _", and the following line includes an extra set of speech marks, where they wouldn't be included if it was on one line, why is this?

Code on one line:

Msg1 = MsgBox("Removing an LPA will remove ALL of their details from the database, including their documents - You cannot undo this action. Do you wish to continue?", vbYesNo, "WARNING!")

Code line separated that works:

Msg1 = MsgBox("Removing an LPA will remove ALL of their details from the database," & _
"including their documents - You cannot undo this action. Do you wish to" & _
" continue?", vbYesNo, "WARNING!")

Code line separated that doesn't work:

Msg1 = MsgBox("Removing an LPA will remove ALL of their details from the database, _
including their documents - You cannot undo this action. Do you wish to _
continue?", vbYesNo, "WARNING!")

So what is the difference between "& _" and " _"?

Can you not continue a string on a new line without closing and opening a new set of speech marks?

Upvotes: 3

Views: 17730

Answers (2)

Krish
Krish

Reputation: 5917

& = join two strings, _ = line separator

unlike c# or Java, VBA code lines does not end with a maker (;), instead VBA IDE uses each line as one code line. which forces you to join strings from each line with the & sign.

also be aware of max line continuation is 25 above this number you will get an error (too many line continuation)

https://msdn.microsoft.com/en-us/library/office/gg264236.aspx

Upvotes: 1

Heinzi
Heinzi

Reputation: 172270

VBA (as well as VB6, VBScript and earlier versions of VB.NET) does not support multi-line string literals:

' Doesn't work
myString = "a
b c"

' Doesn't work either, because _ does not have a special meaning when
' inside double quotes.
myString = "a _
b c"

Thus, you need to split your string into multiple strings. You can concatenate them with the & operator:

myString = "a " & "b c"       ' yields "a b c"

And then you can split your line outside the string at any place between two tokens:

myString = "a " & _
           "b c"              ' my personal preference

' or

myString = "a " _
           & "b c"

' or

myString = "a " _
           & _
           "b c"

' or even

myString _
    = _
    "a " _
    & _
    "b c"

Upvotes: 5

Related Questions