下面是一些小改動的工作小組(看看評論)。我試圖儘可能地堅持原來的代碼,這樣你就可以發現自己。此外,我實現了一些好的編碼實踐,如變量命名和使用.Value2
代替.Value
:
Option Explicit
Option Compare Text
Sub ReplaceTextCellByCell()
Dim shtData As Worksheet
Dim lngLastRow As Long
Dim rngAllData As Range, rngCell As Range
Set shtData = ThisWorkbook.Worksheets("StatementData")
lngLastRow = shtData.Cells(shtData.Rows.Count, "A").End(xlUp).Row
'I exchanged the comma for a colon. The comma would mean
' that you are referring to two cells only. The cell
' A1 and the cell K20 (or whatever the last row is)
' The colon instead means that you want every cell
' between these two to be included in the range
Set rngAllData = shtData.Range("A1:K" & lngLastRow)
'The following line is not necessary. Therefore I commented it out.
'shtData.Activate
For Each rngCell In rngAllData
If InStr(1, rngCell.Value2, "Investor Ref :") Then
rngCell.Value = Replace(rngCell.Value2, "Investor Ref :", "")
End If
Next rngCell
End Sub
以下子是在速度方面在第一子略有改善。此外,現在不再僅根據列A
確定最後一行,而是基於最後一行整體確定。如果您願意,可以再次將其更改。
Option Explicit
Option Compare Text
Sub ReplaceTextWithFind()
Dim shtData As Worksheet
Dim lngLastRow As Long
Dim rngAllData As Range, rngCell As Range, strFirstAddress As String
Set shtData = ThisWorkbook.Worksheets("StatementData")
lngLastRow = shtData.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Set rngAllData = shtData.Range("A1:K" & lngLastRow)
'Based on the example provided by Microsoft here
'https://msdn.microsoft.com/en-us/library/office/ff839746.aspx
With rngAllData
Set rngCell = .Find(What:="Investor Ref :", LookIn:=xlValues)
If Not rngCell Is Nothing Then
strFirstAddress = rngCell.Address
Do
rngCell.Value2 = Replace(rngCell.Value2, "Investor Ref :", "")
Set rngCell = .FindNext(rngCell)
If rngCell Is Nothing Then Exit Sub
If rngCell.Address = strFirstAddress Then Exit Sub
Loop
End If
End With
End Sub
我會去更換,而不是由細胞'設置sdalldata = sd.Range( 「A1」, 「K」 和sdlastrowv)去細胞''然後sdalldata.Replace 「投資者參考:」 「」 '。注意:如果有多餘的空格,它將不會取代它,你確定這個''投資者參考:''不是一個錯字,應該是'「投資者參考:」'而不是? – Sgdva
如果該值存在於單元格中,則**會引發錯誤。你沒有得到錯誤,可能是因爲多餘的空白。 –