vba - 如何使用 VBA 删除整个 Excel 列中的空格?

标签 vba excel

我正在尝试删除“A”列的每个字段中的空格,该空格位于字符串的末尾,一些字符串有 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 的字符串变量中,然后不对它执行任何操作。如果您希望它位于Cell中,则必须将其添加回其中,例如:

Cells(I, "A").Value = 结果

请记住,有一个 Application.Trim 方法实际上可以节省一些循环时间。使用以下代码进行实验:

Dim rng as Range

set rng = Range("A1:A10")
rng.Value = Application.Trim(rng)

关于vba - 如何使用 VBA 删除整个 Excel 列中的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32013844/

相关文章:

algorithm - 在 VBA 中无故跳过循环

c# - Excel 生成 c# 中需要空白列名

php - 如何使用 PHP 将数据添加到现有的 Excel 文件?

excel - WScript.Shell 使 Excel 崩溃

Excel VBA : How to clear contents for specified cells when another cell contains specific text or string

vba - 如何在VBA中设置和获取JSESSIONID cookie?

sql-server - VBA 中的数据转换类型错误

vba - 区分在 application.inputbox 中输入 0 和按取消

sql-server - 在 Excel-VBA/SQL : Login failed for user "testuser" 上

c# - 如何使用c#访问excel中的隐藏列