下面是一些小改动的工作小组(看看评论)。我试图尽可能地坚持原来的代码,这样你就可以发现自己。此外,我实现了一些好的编码实践,如变量命名和使用.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
如果该值存在于单元格中,则**会引发错误。你没有得到错误,可能是因为多余的空白。 –