【问题标题】:Comparing cells from two Excel files比较两个 Excel 文件中的单元格
【发布时间】:2020-04-24 12:10:55
【问题描述】:

我必须比较两个数据库,一个来自患者文档系统,另一个来自设备数据库。这两个数据库都导出为 Excel 文件。

我想比较每个 Excel 文件的一列中的单元格(第一个文件中的 B 列,第二个文件中的 M 列)并确保它们的内容相同。

如果相同,则单元格应变为绿色,否则为红色。

因为我不想每次执行此操作时都触摸代码,所以我创建了一个用户表单来加载两个 Excel 工作表并单击“比较”。

如何比较位于不同 Excel 文件中的这两列中的每个单元格?

我想出了这段代码,它在点击“比较”按钮时执行:

Sub CommandButton3_Click()

Dim BBraunFile
Dim ICMFile
Dim CellsBBraun
Dim CellsICM
Dim CellA
Dim CellB

Set BBraunFile = Workbooks.Open(strFileToOpenBbraun)
Set ICMFile = Workbooks.Open(strFileToOpenICM)

CellsBBraun = BBraunFile.Worksheets("0_Standard-Pat.-Profil").Range("b4:b5000")
CellsICM = ICMFile.Worksheets("ExternalIDs").Range("M2:M5000")

    For Each CellA In CellsBBraun
        Set CellB = ICMFile.Worksheets("ExternalIDs").Range(Cell.Row, 13)
        If CellA.Value = CellB.Value Then
                CellA.Interior.ColorIndex = 3
            Else
                CellA.Interior.ColorIndex = 4
        End If
    Next CellA

End Sub

我收到运行时错误“424:需要对象”。

我环顾四周,但找不到答案。

【问题讨论】:

  • CellsBBraunCellsICM 需要在它们之前有set,它们是对象。您还会遇到Range(Cell.Row, 13) 的问题。单元格未在任何地方声明。

标签: excel vba


【解决方案1】:

这使用字典,你可以使用任何容器,但字典有 .exists 这在这里有帮助。

您还应该声明所有变量的类型,您的当前都是变体。

    Dim BBraunFile As Workbook
    Dim ICMFile As Workbook
    Dim CellsBBraun As Range
    Dim CellsICM As Range

    Set BBraunFile = Workbooks.Open(strFileToOpenBbraun)
    Set ICMFile = Workbooks.Open(strFileToOpenICM)

    'Set your objects
    Set CellsBBraun = BBraunFile.Worksheets("0_Standard-Pat.-Profil").Range("b4:b5000")
    Set CellsICM = ICMFile.Worksheets("ExternalIDs").Range("M2:M5000")

    Dim valdict As Object ' This is late binding add in the scripting runtime library for early binding
    Set valdict = CreateObject("Scripting.Dictionary") ' This is late binding add in the scripting runtime library for early binding

    Dim CellA As Range

    For Each CellA In CellsICM 'Iterate through workbook we aren't formatting
        valdict(CellA.Value) = "" ' Just populating keys we dont need an item
    Next CellA

    For Each CellA In cellsbbraun 'Iterate through workbook we are formatting
        If valdict.exists(CellA.Value) Then 'See if the value is in the dictionary
            CellA.Interior.ColorIndex = 4
        Else
            CellA.Interior.ColorIndex = 3
        End If
    Next CellA

【讨论】:

  • 非常感谢!这成功了。纯粹出于兴趣,这只是比较字典中是否存在值,对吧?它不比较特定的单元格(例如 B2 与 M2、B3 与 M3 等等)?
  • 是的,就像它们在另一张纸上一样。除非您可以保证它们已排序并包含相同数量的值,否则将 B2 与 M2 进行比较可能不起作用。如果是这种情况,您可以跳过字典,只使用行号来比较每个单元格。
猜你喜欢
  • 2011-07-20
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多