【问题标题】:VBA Trying to overwrite matching records and move non-matching records from ws1 to ws2VBA试图覆盖匹配记录并将不匹配的记录从ws1移动到ws2
【发布时间】:2018-07-31 06:16:42
【问题描述】:

自从我编写代码以来已经有好几年了,我已经尝试了许多循环的变体。我也花了很多时间在 StackOverflow 上,我非常感谢你们所做的工作。

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

8 月 1 日更新:我得到了下面的工作,但是,当 ohn 为空时,我需要跳出循环。现在它会正确移动记录,但会继续根据 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

这让我花了好几天没有做任何事情!我终于寻求帮助了。感谢所有帮助!

【问题讨论】:

  • 不正确:(已更新记录信息的LC)。更正:DD 更新了记录信息,因此将 LC 记录替换为匹配的 DD 记录。
  • 如果您编辑您的问题以更正而不是作为评论发布会更好。

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


【解决方案1】:

我在 If ohnDD.Value = ohnLC.Value Then 之前添加了另一个 IF 语句 如果 ohnDD.Value "" 那么

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

【讨论】:

    猜你喜欢
    • 2022-12-07
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    相关资源
    最近更新 更多