vba 判断两张表的其中一列单元格是否相等 if
时间: 2023-08-08 18:05:23 浏览: 192
可以使用VBA编写一个子程序来判断两张表的其中一列单元格是否相等,代码如下:
```
Sub CompareColumns()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim col1 As Range, col2 As Range
Dim lastRow As Long, i As Long
' 设置要比较的两个工作表
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
' 获取要比较的列
lastRow = ws1.Cells(Rows.Count, "A").End(xlUp).Row
Set col1 = ws1.Range("A1:A" & lastRow)
Set col2 = ws2.Range("A1:A" & lastRow)
' 逐个比较单元格
For i = 1 To lastRow
If col1.Cells(i).Value <> col2.Cells(i).Value Then
' 如果有任意一个单元格的值不相等,则退出循环
MsgBox "单元格 " & col1.Cells(i).Address & " 和 " & col2.Cells(i).Address & " 的值不相等!", vbExclamation
Exit Sub
End If
Next
' 所有单元格的值都相等
MsgBox "两张表的指定列的所有单元格的值都相等。", vbInformation
End Sub
```
这个子程序会先获取两个工作表中要比较的列(这里假设是A列),然后逐个比较这两列中的单元格。如果发现任意一个单元格的值不相等,就会弹出一个提示框并退出循环。如果所有单元格的值都相等,则会弹出一个提示框表示指定列的所有单元格的值都相等。
阅读全文
相关推荐















