這是你的代碼的優化版本,在大數據表的情況下:
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
謝謝!我確實是針對錯誤的單元格。facepalm。你爲什麼要設置currentSheet部分並使用當前表?代碼將在默認情況下運行當前活動工作表嗎? – JimJimL
我只是這樣做:)我看到了許多錯誤代碼造成的非正確的參考,並針對錯誤的表,我寧願每次都這樣做。另外,當我看了科迪一段時間後,我仍然知道我想做什麼。 –
如果沒有完全參考工作表,當您說'Cells(row,1)'時,您可以參考任何工作簿當前處於活動狀態的活動工作表。通過完全限定參考資料(本人將以'ThisWorkbook.Sheets(「Sheet1」)'的身份),您確保Excel不會「猜測」您的意思。希望這可以幫助! – asongtoruin