Reputation: 2656
I have cells with data like these:
ABCD123XYZ MPOP345MLU . . . .
What I want to do is, to remove the 3rd and 4th character from all these cells, hence giving
AB123XYZ MP345MLU
How do I do this in VBA?
I have no idea about this language, and if someone can guide me in the right direction, it'd be great :)
I understand I have to:
Upvotes: 1
Views: 179
Reputation: 6323
use the "mid" function
Dim str1 As String
Dim str2 As String
str1 = Cells(1, 1) '"ABCD123XYZ"
str2 = Cells(2, 1) '"MPOP345MLU"
Cells(1, 2) = Mid(str1, 1, 2) & Mid(str1, 5) 'yield AB123XYZ
Cells(2, 2) = Mid(str2, 1, 2) & Mid(str2, 5) 'yield MP345MLU
Upvotes: 1
Reputation: 169274
@DougGlancy's got your answer already,
but if you really want to use VBA:
Sub substr_example()
ThisWorkbook.Sheets(1).Range("B1:B100").FormulaR1C1 = _
"=LEFT(RC[-1],2)&MID(RC[-1],5,LEN(RC[-1])-4)"
End Sub
Upvotes: 1
Reputation: 149287
Another way using Replace() formula where A1 is the cell which has the text. You can simply copy the formula down.
=REPLACE(REPLACE(A1,3,1,""),3,1,"")
VBA CODE
Sub Sample()
Dim LastRow As Long
With Sheets("Sheet1")
LastRow = .Range("A" & Rows.Count).End(xlUp).Row
.Range("B1").FormulaR1C1 = "=REPLACE(REPLACE(RC[-1],3,1,""""),3,1,"""")"
.Range("B1").AutoFill Destination:=Range("B1:B" & LastRow), Type:=xlFillDefault
End With
End Sub
Upvotes: 3
Reputation: 27478
You don't need VBA for this. Just use a formula:
=LEFT(A1,2) & MID(A1,5,9999)
Upvotes: 1