PDA

View Full Version : Need help with loop, concatenate and trim in Excel, VBA



cp713a
01-08-2021, 02:05 PM
Hi,

I need some help. I have a long list of items in column A with extra spaces, such as: Samsung ', I'd like to loop thru the entire column A, trim out all the extra spaces, I think application.worksheetFunction.Trim(A1), then concatenate the a word "Equipment", the output result as: "Samsung Equipment" in the same column A.

I was able to do a single item, but not able to get the loop, which I'm not familiar with.

Much appreciate it,

anish.ms
01-09-2021, 12:05 PM
Attach a sample file. However, the following sample code helps to trim the extra spaces including space with special character code 160
Select the cells with data in column A




Sub RemoveSpaces()
Dim myRange As Range
Dim myCell As Range
Set myRange = Selection
For Each myCell In myRange
If Not IsEmpty(myCell) Then
myCell = Application.WorksheetFunction.Trim(WorksheetFunction.Substitute(myCell, Chr(160), "")) & " Equipment"
End If
Next myCell
End Sub

cp713a
01-11-2021, 12:49 PM
Please see attached file for sample. So, what I'd like to see is in ColA, I have existing data, and I'd like to loop thru and achieved like the Result in ColB, but without dump the data in another column. So, the existing text in ColA, loops thru that entire column, concatenate word 'Equipment', adding single quotes ('Samsung Equipment') like so around the text. Hope this helps and makes sense.

p45cal
01-12-2021, 09:35 AM
Select the cells you want to process first, then try running:
Sub blah()
For Each cll In Selection.Cells
x = Split(cll.Value, "'")
x(0) = x(0) & " Equipment"
cll.Value = Application.Trim(Join(x, "'"))
Next cll
End Sub

snb
01-13-2021, 02:24 AM
Sub M_snb()
sheet1.columns(1).replace " "," "
sheet1.columns(1).replace "'","Equipment'"
End Sub

cp713a
01-15-2021, 04:39 PM
Select the cells you want to process first, then try running:
Sub blah()
For Each cll In Selection.Cells
x = Split(cll.Value, "'")
x(0) = x(0) & " Equipment"
cll.Value = Application.Trim(Join(x, "'"))
Next cll
End Sub



p45cal, this works thank you very much.:yes