如何使用VBA从整个Excel列中删除空格?
我试图删除我在列的每个字段中的空格“A”这个空格在string的末尾某些string有3个空格其他4.当我运行代码时,我没有错误,所以我觉得我有一个错误,因为运行时没有发生任何事情。
Dim result As String Last = Cells(Rows.Count, "A").End(xlUp).Row For i = Last To 1 Step -1 If (Right(Cells(i, "A").Value, 4)) Like " " Or (Right(Cells(i, "A").Value, 3)) Like " " Then result = Replace(Cells(i, "A"), " ", "") End If Next i
目前你实际上并没有更新循环中的单元格,
result = Replace(Cells(i, "A"), " ", "")
你应该:
Cells(i, "A") = Replace(Cells(i, "A"), " ", "")
或更好
Cells(i, "A") = rtrim$(Cells(i, "A"))
这将删除所有正确的空间。 你也可以删除if检查。
在你的具体情况下,问题是你将replace值存储在一个名为result
的stringvariables中,然后什么都不做。 如果你想让它在Cell
,你必须把它添加回来,比如:
Cells(I, "A").Value = result
请记住,有一个Application.Trim
方法实际上可以节省一些循环的时间。 尝试使用如下代码:
Dim rng as Range set rng = Range("A1:A10") rng.Value = Application.Trim(rng)
期待这个代码做什么? 因为目前的价值正在被读入结果。 使用修剪去除尾随空格也会更好。
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