gpt4 book ai didi

VBA:如何比较两个不同工作表中的两列

转载 作者:行者123 更新时间:2023-12-04 20:32:40 28 4
gpt4 key购买 nike

当两列都在同一个工作表中时,我才设法做到这一点。

我想做的事:
比较两个不同工作表(工作表 A 和 B)中的两列。仅存在于工作表 A 但不存在于工作表 B 中的单元格应粘贴到工作表 B 中。仅存在于工作表 B 中但不存在于工作表 A 中的单元格也是如此。我还希望第一行为空的类别。所以它应该从第二行开始计数。

任何人都可以帮忙吗?

Sub test()

Dim d1 As Object, d2 As Object, d3 As Object, e

Set d1 = CreateObject("scripting.dictionary")
Set d2 = CreateObject("scripting.dictionary")
Set d3 = CreateObject("scripting.dictionary")

For Each e In Cells(1).Resize(Cells(Rows.Count, 1).End(3).Row).Value
d1(e) = True
d2(e) = True
Next e

For Each e In Cells(2).Resize(Cells(Rows.Count, 2).End(3).Row).Value
If (d2(e)) * (d1.exists(e)) Then d1.Remove e
If Not d2(e) Then d3(e) = True
Next e

On Error Resume Next
Range("J1").Resize(d1.Count) = Application.Transpose(d1.keys)
Range("K1").Resize(d3.Count) = Application.Transpose(d3.keys)
On Error GoTo 0

End Sub

最佳答案

您必须将单元格、行等引用到给定的工作表。这不是一项艰巨的任务,如果你做得对的话。

看看如何引用工作表:

Sub TestMe()

Dim shA As Worksheet
Dim shB As Worksheet
Dim e As Range

Set shA = Worksheets(1)
Set shB = Worksheets("Tabelle2")

With shA
For Each e In .Cells(1).Resize(.Cells(.Rows.Count, 1).End(3).Row)
Debug.Print e.Address
Next e
End With
End Sub

如您所见,方法主要有两种:
  • 按索引 - Set shA = Worksheets(1)
  • 按名称 - Set shB = Worksheets("Tabelle2")

  • 还有第三种方法,通过 vba 的对象名称,但您现在可能不需要它。在上面的示例中,请注意您对父级 shA 引用了 3 次。在这一行:
    For Each e In .Cells(1).Resize(.Cells(.Rows.Count, 1).End(3).Row)
  • .Cells(1)...
  • .(Cells(...
  • .Rows.Count,..

  • 这是相当重要的,当使用工作表时,可能是 StackOverflow 中的第一个错误,人们在使用 VBA 时会这样做。例如。这里 - VBA Runtime error 1004 when trying to access range of sheetVBA - Getting a runtime error '1004' when running this code

    如果您错过了三个时间引用, CellsRows从上述范围将自动引用 ActiveSheet .这可能并不总是理想的情况。

    关于VBA:如何比较两个不同工作表中的两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47714981/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com