다음은 약간의 변경 사항이있는 작업 하위 항목입니다 (주석 참조). 가능한 한 많이 원래 코드를 고수하려고 했으므로 코드를 찾을 수있었습니다. 또한, 나는 그런 변수의 이름과 .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
다음 서브 속도의 측면에서 제 1 서브에 비해 약간의 개선이다. 또한 마지막 행은 더 이상 열 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
**이 값은 셀에 값이 있으면 오류가 발생합니다 **. 아마도 여분의 공백으로 인해 오류가 발생하지 않을 것입니다. –