Extracting Text from Cell, VBA Loop

cart0250

Active Member
Joined
Jun 24, 2006
Messages
284
Office Version
  1. 2016
Platform
  1. Windows
Good day;

I am trying to loop through a column and remove all characters to the right of the Final comma (including the comma itself) in each cell of that column using VBA.
For example, if cell contains: test, test2, test3
I would like to remove the ", test3" so the string now shows as "test, test2"

Problem w/ my code below is the len2 variable seems to be finding the length of string to the left of first comma, instead of length of string to Right of Final comma. Can someone help modify this, or else suggest different way?

Thank you.

VBA Code:
For i = lastRow to 2 step -1
    len1 = Len(.Cells(i,"A").Value) ' length whole string
    len2 = Len(Right(.Cells(i,"A").Value, Instr(.Cells(i,"A").Value, ",")+1)) 
    .Cells(i,"A").Value = Left(.Cells(i,"A").Value, len1-len2)) 
Next i
 

Excel Facts

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).
Try this:
VBA Code:
For i = lastRow to 2 step -1
   len2 = InStrRev(.Cells(i, "A").Value, ",")
  .Cells(i, "A").Value = Left(.Cells(i, "A").Value, len2)
Next i
 
Upvote 0
Try this:
VBA Code:
For i = lastRow to 2 step -1
   len2 = InStrRev(.Cells(i, "A").Value, ",")
  .Cells(i, "A").Value = Left(.Cells(i, "A").Value, len2)
Next i
Thank you both! This works with -1 on the len2 to remove the comma.
 
Upvote 0

Forum statistics

Threads
1,214,649
Messages
6,120,728
Members
448,987
Latest member
marion_davis

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