通过VBA对比两个Excel文件的内容
通过VBA对比两个文件的不同,代码如下:
Sub 比较Excel变化()
Dim oldFilePath As String
Dim newFilePath As String
Dim oldworkbook As Workbook
Dim newworkbook As Workbook
Dim oldSheet As Worksheet
Dim newSheet As Worksheet
Dim oldCell As Range
Dim newCell As Range
'选择旧文件
1
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "选择旧文件"
If .Show <> -1 Then
If MsgBox("未选择文件,是否重新选择", vbOKCancel) = vbOK Then
GoTo 1
Else
End
End If
End If
Set oldworkbook = Workbooks.Open(.SelectedItems(1))
End With
'选择新文件
2
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "选择新文件"
If .Show <> -1 Then
If MsgBox("未选择文件,是否重新选择", vbOKCancel) = vbOK Then
GoTo 2
Else
End
End If
End If
Set newworkbook = Workbooks.Open(.SelectedItems(1))
End With
' 比较每个工作表中的单元格
For Each newSheet In newworkbook.Sheets
Set oldSheet = oldworkbook.Sheets(newSheet.Name)
' 比较每个单元格的值
For Each newCell In newSheet.UsedRange
Set oldCell = oldSheet.Range(newCell.Address)
' 如果单元格的值不相等,则在新文件中标记为变化
If newCell.Value <> oldCell.Value Then If newCell.Value <> oldCell.Value Then
newCell.Interior.Color = RGB(255, 0, 0) ' 标记为红色 newCell.Interior.Color = RGB(255, 0, 0) ' 标记为红色
End If 结束如果
Next newCell Next newCell
Next newSheet Next newSheet
' 关闭文件 Close the file
oldworkbook.Close SaveChanges:=True 旧工作簿。关闭 SaveChanges:=True
newworkbook.Close SaveChanges:=True NewWorkBook。关闭 SaveChanges:=True
' 提示比较完成 Prompt comparison complete
MsgBox "Excel文件比较完成!" MsgBox "Excel文件比较完成!"
End Sub 结束子
使用方法:
How to use:
源文件地址:https://www.123pan.com/s/iciVVv-wfBk3.html The address of the source file
共有 0 条评论