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

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.

Forum statistics

Threads
1,215,743
Messages
6,126,603
Members
449,321
Latest member
syzer

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