ここにはマイナーな変更が加えられた作業用サブがあります(コメントを見てください)。私は可能な限り元のコードに固執して、自分自身を見つけることができました。また、私はこのような変数の命名と.Value
の代わり.Value2
を使用するなど、いくつかの良いコーディングプラクティスを実装:
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.Replace "投資参考:" セル '設定しsdalldata = sd.Range( "A1"、 "K" &sdlastrowv)によって細胞を行くの置き換えのために行くだろう "" '。注意:余分な空白がある場合、それを置き換えることはありません。これは本当に '' Investor Ref: ''は誤字ではなく、代わりに '' Investor Ref: "'でしょうか? – Sgdva
この**は、値がセルに存在する場合にエラーを発生させます**。おそらく特別な空白のためにエラーが発生することはありません。 –