在VBA中循环修剪一个单元格

我试图使用修剪function没有成功。 在网上search这个论坛和其他资源的解决scheme后,我看到了许多不同的方法。

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)列中的值应该被修剪为任何额外的空格。 我只是不能让这个为我工作。

感谢任何帮助/提示!

问候吉姆

所以我让代码有点准确和错误的,它的工作。

所以我可以推荐你仔细检查,如果你有正确的行和列值,因为你可能定位错误单元格。 (导致你的代码正在工作)

 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 

使用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 

这是您的代码的优化版本,在大数据表的情况下:

 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