我要检查一个工作簿中A列的内容是否等于另一工作簿中A列的内容。
每个单元格应该相同。
我能找到的最好的是:
Sub RowCompare()
Dim ary1() As Variant
Dim Range1 As Range, Range2 As Range, rr1 As Range, rr2 As Range
Set Range1 = Range("B9:F20")
Set Range2 = Range("I16:M27")
Set rr1 = Range1.Rows(5)
Set rr2 = Range2.Rows(5)
ary1 = Application.Transpose(Application.Transpose(rr1))
ary2 = Application.Transpose(Application.Transpose(rr2))
st1 = Join(ary1, ",")
st2 = Join(ary2, ",")
If st1 = st2 Then
MsgBox "the same"
Else
MsgBox "different"
End If
End Sub
答案 0 :(得分:0)
设置Workbook
和Worksheet
时,您需要在Range
之前指定Range1
和Range2
例如,进行以下编辑:
Set Range1 = Workbooks("workbook 1 name").Worksheets("your sheet name").Range("B9:F20")
Set Range2 = Workbooks("workbook 2 name").Worksheets("other sheet name").Range("I16:M27")
此外,我看到您是从Fastest way to check if two ranges are equal in excel vba抢来的
答案 1 :(得分:0)
Sub CompareColumns()
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2")
Dim Arr1 As Variant, Arr2 As Variant
Dim i As Long, Same As Boolean
'Assume they are the same before starting loop
Same = True
'Assign some range to Array
Arr1 = ws1.Range("A1:A20").Value
Arr2 = ws2.Range("A1:A20").Value
'Loop through Array
For i = LBound(Arr1) To UBound(Arr2)
If Arr1(i, 1) <> Arr2(i, 1) Then
Same = False
End If
Next i
'Check the value of "Same"
If Same = False Then MsgBox "Ranges are not equal!"
End Sub