VBA尝试覆盖匹配的记录并将不匹配的记录从ws1移动到ws2

时间:2018-07-31 06:16:42

标签: excel vba for-loop if-statement do-while

我编码已经有很多年了,我已经尝试了许多循环形式。我还在StackOverflow上花了很多时间,对于你们所做的工作我感到非常满意。

我有2张纸和1本工作簿。 Sheet1 = DD,并且具有比工作表2多的数千条记录。DD已更新记录信息。 DD中的所有记录都需要移至LC。但是,有许多记录从DD到LC匹配,并且DD的整个行都需要替换LC行。如果DD中的值与LC中的现有记录不匹配,则需要将整行移动到LC的末尾。

8月1日更新:我可以进行以下操作,但是,当ohn为null时,我需要跳出循环。现在,它可以正确移动记录,但是会继续根据DD空值搜索LC。

Dim wsDD As Worksheet, wsLC As Worksheet 'shortens the names for each worksheet (ws) and records range (rng)
Dim rngDD As Range, rngLC As Range, colRng As Range
Dim lastRowDD As Long, lastRowLC As Long
Dim lastUIDused As Long 'holds the value of the last LC Unique ID when UniqueID col sorted by small-large
Dim ohnDD As Range, ohnLC As Range 'Old Host Number in DD or LC

Set wsDD = ThisWorkbook.Sheets("DataDump")
Set wsLC = ThisWorkbook.Sheets("LifeCycleAllRecs")
Set rngDD = wsDD.Range("A2", wsDD.Range("A" & wsDD.Cells(Rows.Count, 1).End(xlUp).Row)) 'finds & stores range of all used rows and columns in DataDump
Set rngLC = wsLC.Range("A2", wsLC.Range("A" & wsLC.Cells(Rows.Count, 1).End(xlUp).Row)) 'finds & stores range of all used rows and columns in LifeCycle

lastRowDD = wsDD.Range("A" & Rows.Count).End(xlUp).Row                              'stores last row # in DataDump
lastRowLC = wsLC.Range("A" & Rows.Count).End(xlUp).Row                              'stores last row # in LifeCycle tab

----------------- example 1-------------------
Set ohnDD = wsDD.Range("A2")
Set ohnLC = wsLC.Range("A2")
'for each cell in DD column, match with a cell in LC and return row number
'replace LC row with matching DD row
wsDD.Activate
    For Each ohnDD In wsDD.Range("Q1:Q" & lastRowDD)
        If ohnDD.Value > 0 Then 'ONLY IF NOT BLANK
            For Each ohnLC In wsLC.Range("X2:X" & lastRowLC)
                      MsgBox "2nd for ohndd " & ohnDD & "    ohnlc " & ohnLC
                      'And ohnDD.Value <> ""
                If ohnDD.Value = ohnLC.Value Then
                    wsDD.Range("A" & ohnDD.Row & ":U" & ohnDD.Row).Cut wsLC.Range("H" & ohnLC.Row)
                Else
                End If
            Next ohnLC
        Else
        End If
    Next ohnDD

这让我花了几天时间做其他事情!我终于在寻求帮助。我感谢所有帮助!

1 个答案:

答案 0 :(得分:0)

我在If ohnDD.Value = ohnLC.Value之前添加了另一个IF语句 如果ohnDD.Value <>“”然后

似乎正在工作。一周的斗争终于结束了!