How to remove spaces from an entire Excel column using VBA?

后端 未结 3 616
我寻月下人不归
我寻月下人不归 2021-01-14 15:31

I\'m trying to delete the spaces that I have in each field of the column \"A\" this spaces are at the end of the string some of the string has 3 spaces others 4. When I run

相关标签:
3条回答
  • 2021-01-14 16:01

    In your specific case, the problem is that you're storing the replacement value in a string variable named result, then doing nothing with it. If you want it to be in the Cell, you have to add it back in there, such as:

    Cells(I, "A").Value = result

    Keep in mind, there is an Application.Trim method that can actually save a bit of time over looping. Experiment with code such as:

    Dim rng as Range
    
    set rng = Range("A1:A10")
    rng.Value = Application.Trim(rng)
    
    0 讨论(0)
  • 2021-01-14 16:05

    Currently you are not actually updating the cell in the loop, you just;

    result = Replace(Cells(i, "A"), " ", "")
    

    You should:

    Cells(i, "A") = Replace(Cells(i, "A"), " ", "")
    

    Or better

    Cells(i, "A") = rtrim$(Cells(i, "A"))
    

    Which will remove all right spaces. You can probably remove the if check as well.

    0 讨论(0)
  • 2021-01-14 16:06

    What are expecting this code to do? as currently the values are being read into result. It would also be better to use trim to remove trailing spaces.

    Dim result As String
    Last = Cells(Rows.Count, "A").End(xlUp).Row
        For i = Last To 1 Step -1
            result = RTrim(Cells(i, "A"))
        Next i
    
    0 讨论(0)
提交回复
热议问题