如何比较不同excel文件中的2个列表并突出显示更改?

时间:2013-01-29 04:38:09

标签: excel excel-vba vba

让18jan.xlsx包含以下数据:

ABC 10
XYZ 20
PQR 30
STU 40
DEF 50
HIJ 60
KLM 70

19jan.xlsx包含:

XYZ 20
ABC 15
STU 40
DEF 50
HIJ 65
PQR 30
KLM 70

我需要比较它们并突出显示更改,例如,应该突出显示ABC前面的15。此外,我还需要每天更改日期。

1 个答案:

答案 0 :(得分:0)

假设您的数据放在第1行的第A:B列中,以下代码应该可以完成这项任务:

Sub DailyDataHighlight()

Dim InputFolder As String
Dim OldExcel As String
Dim NewExcel As String

Dim i As Long
Dim OldString As String
Dim OldValue As String
Dim NewValue As String
Dim SearchResult As Range

InputFolder = "D:\DOCUMENTS\"
OldExcel = "18jan.xlsx"
NewExcel = "19jan.xlsx"

Application.ScreenUpdating = False

Application.Workbooks.Open (InputFolder & OldExcel)
Application.Workbooks.Open (InputFolder & NewExcel)

For i = 1 To Workbooks(OldExcel).ActiveSheet.Range("A1").CurrentRegion.Rows.Count

    OldString = Workbooks(OldExcel).ActiveSheet.Cells(i, 1).Text
    OldValue = Workbooks(OldExcel).ActiveSheet.Cells(i, 2).Text
    Set SearchResult = Workbooks(NewExcel).ActiveSheet.Range("A1").CurrentRegion
    Set SearchResult = SearchResult.Find(OldString, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True)
    If Not SearchResult Is Nothing Then
        NewValue = SearchResult.Offset(0, 1).Text
        If NewValue <> OldValue Then SearchResult.Offset(0, 1).Interior.Color = RGB(0, 255, 0)
    End If

Next i

Workbooks(NewExcel).Save
Application.ScreenUpdating = True

End Sub

假设和细节:

  1. 数据范围实际上是无限的。
  2. 两个文件都放在同一个文件夹中。姓名&amp;路径应该用代码定义。
  3. 使用单元格填充“突出显示”,根据需要更改.Interior.Color = RGB(0, 255, 0)
  4. 仅检查第一个且仅出现的密钥字符串是否有变化(基于输入)。
  5. 示例文件也是共享的:https://www.dropbox.com/s/vqkulovmg98yaih/DailyDataHighlight.xlsm

    希望这对学习VBA很有帮助。