2017-07-20 92 views
0

我有一個設置與板材中的列列d和重置價值的唯一標識符F.我需要:Excel的VBA - 搜索,偏移,更換

  • 遍歷所有序列號在片settings列d
  • 找到具有相同序列的行中片test塔A
  • 得到settings F列
  • 替換值替換在列B中的數據上test片,在同一行中作爲先前擊發阻鐵高等教育委員會串行

聽起來很簡單,但與下面的代碼定義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

+0

當cell崩潰時'cell.Value'和'cell.Offset(0,2).Value'的值是什麼? – YowE3K

+0

'cell.value'是它應該查找的序列號,而'cell.offset(0,2).value'是替換值 – Armitage2k

+0

但是它崩潰時的值是什麼?例如。它是否大於2,147,486,647? – YowE3K

回答

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 
+0

'end if if if if'錯誤 – Armitage2k

+0

@ Armitage2k哎呀 - 愚蠢的錯誤 - 固定(希望) - 也改變了'循環while'之前的行 - 不知道這是否也會導致問題(我不使用'查找'很多),但決定改變它無論如何 – YowE3K

+0

永遠不要急於你的午餐休息;)非常感謝,它現在完美的作品,感謝幫助! – Armitage2k