在循环中使用VBA修剪单元格

时间:2016-03-07 09:14:52

标签: excel vba excel-vba

我正在尝试使用trim功能但没有成功。在网上搜索解决方案和其他来源后,我看到了很多不同的方法。

在VBA中没有简单的方法来修剪单元格吗?

我想要的是这样的:

Sub trimloop()

Dim row As Integer

row = 1

Do While Cells(row, 1) <> ""

   Cells(row, 2) = trim(Cells(row, 2))

   row = row + 1

Loop

因此,当A(1)列中有值时,应修剪B(2)列中的值,以修剪任何多余的空格。我不能让这个为我工作。

感谢任何帮助/提示!

此致 吉姆

4 个答案:

答案 0 :(得分:2)

所以我使代码有点准确和错误,并且有效。

所以我建议你仔细检查,如果你有正确的行和列值,因为你可能针对错误的单元格。 (导致你的代码正常工作)

Sub trimloop()

Dim row As Integer
Dim currentSheet As Worksheet
Set currentSheet = sheets("Sheet1")

row = 2

Do While currentSheet.Cells(row, 1) <> ""

   currentSheet.Cells(row, 2).Value = Trim(currentSheet.Cells(row, 2).Value)

   row = row + 1

Loop

End Sub

答案 1 :(得分:1)

使用Application.WorksheetFunction.Trim(string)

Sub trimloop()

Dim row As Integer

row = 1

With ThisWorkbook.ActiveSheet
Do While .Cells(row, 1) <> ""

   .Cells(row, 2) = Application.WorksheetFunction.Trim(.Cells(row, 2))

   row = row + 1

Loop
End With
End Sub

答案 2 :(得分:1)

这是代码的优化版本,如果是大数据表:

Option Explicit

Sub trimloop()

Dim row As Long, max As Long
Dim Data() As Variant

With ThisWorkbook.Sheets(1)

    max = .Cells(1, 1).End(xlDown).row 'this does the same as your code, on first empty cell it stops
    'the following finds the last un-empty cell of column(1):
    'max= .cells(.rows.count,1).end(xlup).row

    'copies values from sheet to memory (is faster for working with later)
    Data = .Range(.Cells(1, 1), .Cells(max, 2)).Value2

    'loop :
    For row = 2 To max + 1

        'work with memory instead of sheet
        Data(row, 2) = Trim(Data(row, 2))
        'for complete delete of all spaces use : = replace( StringName," ", "")

    Next row

    'write back to sheet
    .Range(.Cells(1, 1), .Cells(max, 2)).Value2 = Data

End With

erase Data 'free memory

End Sub

答案 3 :(得分:0)

不知道这是否过于简化...但以为我会简单地将其扔掉,这对我有用。唯一的先前步骤是为工作簿/工作表/数据集分配“命名范围” ...命名数据集,然后使用此代码遍历数据集

Sub forEachLoop()
    For Each cell In Range("yourNamedRange")
        cell.Value = Trim(cell.Value)
    Next cell
End Sub