[英]Trim a cell with VBA in a loop
我試圖使用修剪功能沒有成功。 在此論壇和其他在線資源上搜索解決方案后,我發現了許多不同的方法。
在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
不知道這是否過於簡化...但是我想我只是把它扔出去,對我有用。 唯一的先前步驟是為工作簿/工作表/數據集分配“命名范圍” ...命名數據集,然后使用此代碼遍歷數據集
Sub forEachLoop()
For Each cell In Range("yourNamedRange")
cell.Value = Trim(cell.Value)
Next cell
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.