Curious use of VBA Mid() function

Richard Schollar

MrExcel MVP
Joined
Apr 19, 2005
Messages
23,707
Not a question - just sharing an interesting use of the VBA Mid() function.

Did you know you can use Mid to assign a replacement string of the same size into a variable:

Rich (BB code):
Dim s As String
s = "True fact: Fred is a hero!"
Mid(s,Instr(1,s,"Fred",vbBinaryCompare)) = "Rich"
MsgBox s
'... Produces:
'... True fact: Rich is a hero!

The code in red is an assignment not a comparison! Looks utterly crazy to me. Not sure this is much (if any) use in the real world, but is is facinating!
 
I have used this, but not very often.

But in playing with it today, I found that the replacement string can be longer than what you actually use, it will use the number of characters specified in the MID statement.

Code:
Sub test2()
Dim t As String, r As String
t = "This is test"
r = "a fun"
Mid(t, 6, 2) = r
MsgBox t
End Sub
 
Upvote 0

Excel Facts

Who is Mr Spreadsheet?
Author John Walkenbach was Mr Spreadsheet until his retirement in June 2019.

Forum statistics

Threads
1,223,911
Messages
6,175,326
Members
452,635
Latest member
laura12345

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top