Reputation: 155
I want to manipulate some Excel sheets using VBA. I have already managed to copy data across to the appropriate cells, but now I need to remove some characters that appear after the first blank space from a range of cells.
I don't know know the last cell number in the column so I have to find out what that cell number is first.
This is a sample of the data in the cells:
IT - Information Technology
IB6 - Information Business
I want to leave :
IT
IB6
and remove the rest of the cell contents. This is the script that I am using:
Dim strCoIDFull As String
Dim strCoIDShrt As String
'remove characters after the first blank space in column M 'Department Code'
LastRow = Cells(Rows.Count, 13).End(xlUp).Row
strCoIDFull = Range("M22:M" & LastRow).Value
strCoIDShrt = Left(CompanyIDFull, InStr(strCoIDFull, " ") - 1)
Range("M22:M" & LastRow).Value = strCoIDShrt
This section of the VBA code does not work, any ideas on where I have gone wrong or a better solution??
Upvotes: 0
Views: 633
Reputation: 34055
All you really need is this:
Dim LastRow As Long
LastRow = Cells(Rows.Count, "M").End(xlUp).Row
Range("M22:M" & LastRow).Replace what:=" *", replacement:="", lookat:=xlPart
Upvotes: 0
Reputation: 9444
There are two problems:
(1) The following row
strCoIDShrt = Left(CompanyIDFull, InStr(strCoIDFull, " ") - 1)
probably needs to be changed to
strCoIDShrt = Left(strCoIDFull, InStr(strCoIDFull, " ") - 1)
(2) Once you have done the above you will probably get the truncated value for M22 in all other rows too. That's because you are missing a loop. You need to iterate through the rows in order to truncate each row and each string within. For more information on loops you might want to check out the following link: http://www.homeandlearn.org/excel_vba_for_loops.html
Upvotes: 0