Trim left characters excel vba

Apple08

Active Member
Joined
Nov 1, 2014
Messages
450
Hi everyone

I have a problem to trim the left characters of a cell, if the column E cell value starts with P or M, then the first left two characters have to trim off, if it starts with X, then the left four characters have to trim off.

I have done the vba as follows but it doesn't work, please can anyone help?

HTML:
Dim i As Long
Dim lastrow As Long
lastrow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow
If Cells(i, 5).Value Like "P-*" Or Cells(i, 5).Value Like "M-*" Then
Cells(i, 5).value = Right((i,5), Len((i,5) - 2)
Else
If Cells(i, 5).Value Like "Z*" Then Cells(i, 5).Value = Right((i,5), Len(i,5) - 4)
End If
End If
        
    Next I
 

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December
Code:
Dim thisRow As Long
Dim lastRow As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row

For thisRow = 2 To lastRow
    If Left$(Cells(thisRow, 5).Value, 2) = "P-" Or Left$(Cells(thisRow, 5).Value, 2) = "M-" Then
        Cells(thisRow, 5).Value = Mid$(Cells(thisRow, 5).Value, 3)
    ElseIf Left$(Cells(thisRow, 5).Value, 1) = "Z" Then
        Cells(thisRow, 5).Value = Mid$(Cells(thisRow, 5).Value, 5)
    End If
Next thisRow

WBD
 
Upvote 0
Here is another macro that should also work...
Code:
[table="width: 500"]
[tr]
	[td]Sub Test()
  Dim Addr As String
  Addr = "A2:A" & Cells(Rows.Count, "A").End(xlUp).Row
  Range(Addr) = Evaluate(Replace("IF((LEFT(@)=""P"")+(LEFT(@)=""M""),MID(@,3,LEN(@)),IF(LEFT(@)=""X"",MID(@,5,LEN(@)),IF(@="""","""",@)))", "@", Addr))
End Sub[/td]
[/tr]
[/table]
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,651
Messages
6,120,744
Members
448,989
Latest member
mariah3

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