14

I just need to know how to have plain text and a variable in a messagebox.

For example:

I can do this: MsgBox(variable)

And I can do this: MsgBox("Variable = ")

But I can't do this: MsgBox("Variable = " + variable)

Mark Kramer
  • 3,134
  • 7
  • 34
  • 52

5 Answers5

21

As has been suggested, using the string.format method is nice and simple and very readable.

In vb.net the " + " is used for addition and the " & " is used for string concatenation.

In your example:

MsgBox("Variable = " + variable)

becomes:

MsgBox("Variable = " & variable)

I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx

maybe call

variable.ToString()

update:

Use string interpolation (vs2015 onwards I believe):

MsgBox($"Variable = {variable}")
Ric
  • 12,855
  • 3
  • 30
  • 36
  • 2
    Yep, `(String1 + String2)` and `(String1 & String2)` are both fine, but if want to concatenate a String and an Integer, you need `&`. Just ran into this issue today. – TylerH Apr 25 '17 at 18:28
  • That'd be much more verbose than simply using `&`, wouldn't it? – TylerH Apr 25 '17 at 18:33
  • Only slightly. Very readable and you could also use string interpolation depending on which .net version you use. – Ric Apr 25 '17 at 19:10
5

Why not use:

Dim msg as String = String.Format("Variable = {0}", variable)

More info on String.Format

IAbstract
  • 19,551
  • 15
  • 98
  • 146
0

I kind of run into the same issue. I wanted my message box to display the message and the vendorcontractexpiration. This is what I did:

Dim ab As String
Dim cd As String

ab = "THE CONTRACT FOR THIS VENDOR WILL EXPIRE ON "
cd = VendorContractExpiration


If InvoiceDate >= VendorContractExpiration - 120 And InvoiceDate < VendorContractExpiration Then

MsgBox [ab] & [cd], vbCritical, "WARNING"

End If
Alex K
  • 22,315
  • 19
  • 108
  • 236
0
MsgBox("Variable {0} " , variable)
Muhammad Saeed
  • 81
  • 3
  • 10
0

I wanto to display the count of rows in the excel sheet after the filter option has been applied.

So I declared the count of last rows as a variable that can be added to the Msgbox

Sub lastrowcall()
Dim hm As Worksheet
Dim dm As Worksheet
Set dm = ActiveWorkbook.Sheets("datecopy")
Set hm = ActiveWorkbook.Sheets("Home")
Dim lngStart As String, lngEnd As String
lngStart = hm.Range("E23").Value
lngEnd = hm.Range("E25").Value
Dim last_row As String
last_row = dm.Cells(Rows.Count, 1).End(xlUp).Row

MsgBox ("Number of test results between the selected dates " + lngStart + " 
and " + lngEnd + " are " + last_row + ". Please Select Yes to continue 
Analysis")


End Sub
Cristiano Casciotti
  • 1,016
  • 10
  • 21
Gowtham
  • 1
  • 2