Are VBA strings immutable?

They are immutable, except when they exhibit mutable behaviour, then they are not.

For example assignment via mid$() is significantly faster than a normal new-string-from-assignment.

Dim s As String

s = "ABC"

Debug.Print s, StrPtr(s)

'// -> ABC            122899836

Mid$(s, 1, 1) = "Z"

Debug.Print s, StrPtr(s)

'// -> ZBC            122899836     

s = "??" & Right$(s, 1)

Debug.Print s, StrPtr(s)

'// -> ??C            196635748 

While VB.NET strings are immutable, as mandated by System.String, VBA (including VB6?) strings can be mutated (such as with Mid$). See Alex K's answer and note the StrPtr result after the operations.


Original answer; supported by documentation, in opposition to a counter-example.

VBA strings are immutable.

Just as with VB.NET, there is no way to "replace part of" or "append to" a string without creating a new string. Whether or not this matters - as modern computers are pretty darn fast - depends on the actual algorithm, data, and environment.


Unlike .NET documentation, such a behavior reference for VBA is [becoming] difficult to track down. From MS-VBAL: 2.1 Data Values and Value Types, we find this rare little gem

Individual data values are immutable. This means that there are no defined mechanisms available within a VBA Environment that can cause a data value to change into another data value.

where Strings represent "individual data values".

Tags:

String

Excel

Vba