Excel VBAreplace不执行

我有下面的代码,我正在尝试用“”来replace表单上的文本。 当我运行代码时,我没有收到错误,但没有任何更改,所以它必须在后端运行,但没有正确的指令。 任何想法为什么这可能是?

Sub Replacetext Dim sd As Worksheet Set sd = Sheets("StatementData") Dim sdlastrowv As Long sdlastrowv = sd.Cells(sd.Rows.Count, "A").End(xlUp).Row Dim sdalldata As Range, sdcel As Range, sdcelv As String Set sdalldata = sd.Range("A1", "K" & sdlastrowv) sd.Activate For Each sdcel In sdalldata If InStr(1, sdcelv, "Investor Ref :") Then sdcel.Value.Replace What:="Investor Ref :", Replacement:="" End If Next sdcel End Sub 

这里有一些小改动的工作小组(看看评论)。 我试图尽可能地坚持原来的代码,所以你可以find自己的代码。 此外,我实现了一些良好的编码实践,如命名variables和使用.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 

代码应该是:

 Sub Replacetext() Dim sd As Worksheet Set sd = Sheets("StatementData") Dim sdlastrowv As Long sdlastrowv = sd.Cells(sd.Rows.Count, "A").End(xlUp).Row Dim sdalldata As Range, sdcel As Range, sdcelv As String Set sdalldata = sd.Range("A1", "K" & sdlastrowv) sd.Activate For Each sdcel In sdalldata If InStr(1, sdcel, "Investor Ref :") Then sdcel.Replace What:="Investor Ref :", Replacement:="" End If Next sdcel End Sub 

sdcelv更改为sdcelsdcel.Value.Replace ...更改为sdcel.Replace ...