我有一个设置表,在D列中有唯一标识符,在F列中有替换值。我需要:
settings
列D test
列A settings
列F test
表格中B列中与先前搜索过的序列相同的行中的数据听起来很简单,但在使用下面的代码定义for
和to
语句时,我遇到类型不匹配错误。
Sub Replace_List()
Dim rList As Range, cell As Range, n As Long
Application.ScreenUpdating = False
With ThisWorkbook.Sheets("Settings")
Set rList = .Range("D4", .Range("D" & Rows.Count).End(xlUp))
End With
For Each cell In rList
For n = cell.Value To cell.Offset(0, 2).Value Step 1
ThisWorkbook.Sheets("test").Columns("B:B").Replace What:=n, _
Replacement:=cell.Offset(0, 2).Value, _
LookAt:=xlWhole
Next n
Next cell
Application.ScreenUpdating = True
MsgBox "Replaced all items from the list.", vbInformation, "Replacements Complete"
End Sub
对于我在这里做错的任何指示都表示赞赏。 谢谢, A2k
修改 屏幕截图如下:
答案 0 :(得分:2)
我相信您希望使用Find
查找每个匹配项,然后使用找到的位置Offset
替换该值:
Sub Replace_List()
Dim rList As Range, cel As Range, n As Long
Dim fnd As Range
Dim fndFirst As String
Application.ScreenUpdating = False
With ThisWorkbook.Sheets("Settings")
Set rList = .Range("D4", .Range("D" & .Rows.Count).End(xlUp))
End With
For Each cel In rList
Set fnd = ThisWorkbook.Worksheets("test").Columns("A:A").Find(What:=cel.Value, LookAt:=xlWhole)
If Not fnd Is Nothing Then
fndFirst = fnd.Address
Do
fnd.Offset(0, 1).Value = cel.Offset(0, 2).Value
Set fnd = ThisWorkbook.Worksheets("test").Columns("A:A").FindNext(After:=fnd)
Loop While fnd.Address <> fndFirst
End If
Next
Application.ScreenUpdating = True
MsgBox "Replaced all items from the list.", vbInformation, "Replacements Complete"
End Sub