写个VBA,比对两个excel文档的第一行的各个字段的区别,把有区别的地方标黄
时间: 2024-02-27 12:55:51 浏览: 97
好的,以下是实现该功能的VBA代码:
```
Sub CompareExcel()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim i As Integer, j As Integer
Dim lastCol1 As Integer, lastCol2 As Integer
'打开第一个文档
Set wb1 = Workbooks.Open("文件路径1")
Set ws1 = wb1.Sheets(1)
'打开第二个文档
Set wb2 = Workbooks.Open("文件路径2")
Set ws2 = wb2.Sheets(1)
'获取第一个文档的最后一列
lastCol1 = ws1.Cells(1, Columns.Count).End(xlToLeft).Column
'获取第二个文档的最后一列
lastCol2 = ws2.Cells(1, Columns.Count).End(xlToLeft).Column
'比对两个文档的第一行
For i = 1 To lastCol1
For j = 1 To lastCol2
If ws1.Cells(1, i) = ws2.Cells(1, j) Then
If ws1.Cells(1, i).Value <> ws2.Cells(1, j).Value Then
ws1.Cells(1, i).Interior.Color = vbYellow
ws2.Cells(1, j).Interior.Color = vbYellow
End If
End If
Next j
Next i
'关闭文档
wb1.Close
wb2.Close
End Sub
```
你可以将文件路径1和文件路径2替换成你实际的文件路径。请注意,在运行该代码之前,确保把两个文档都保存并关闭了,否则会出现错误。
阅读全文