简体   繁体   中英

How to remove characters in a cell after the first blank space using VBA?

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??

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM