Excel VBA - 搜索,偏移,替换

时间:2017-07-20 03:02:35

标签: excel vba excel-vba

我有一个设置表,在D列中有唯一标识符,在F列中有替换值。我需要:

  • 遍历工作表settings列D
  • 中的所有序列号
  • 在工作表test列A
  • 中找到具有相同序列的行
  • settings列F
  • 获取替换值
  • 替换test表格中B列中与先前搜索过的序列相同的行中的数据

听起来很简单,但在使用下面的代码定义forto语句时,我遇到类型不匹配错误。

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

修改 屏幕截图如下:

设置 - 我正在查找调查ID,并希望将原始日期替换为正确日期 enter image description here

1 个答案:

答案 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