If d.exists(ky) = True And d1.exists(ky) = True Then
ReDim Preserve Ar(s) '相同
Ar(s) = ky
s = s + 1
Else
ReDim Preserve Ay(k) '不同
Ay(k) = ky
k = k + 1
End If
Next
With Sheet3
.Cells = ""
.[A1].Resize(s, 1) = Application.Transpose(Ar)
.[B1].Resize(k, 1) = Application.Transpose(Ay)
End With
End Sub
複製代碼
作者: Andy2483 時間: 2022-10-18 16:43
謝謝前輩們
今天練習陣列與字典
Option Explicit
Sub TEST()
Dim i&, x&, Y, Z
Set Y = CreateObject("Scripting.Dictionary")
Set Z = CreateObject("Scripting.Dictionary")
For x = 1 To 2
Y(x) = Sheets(x).Range("A1:A" & Sheets(x).[A65536].End(3).Row)
Y(x) = Application.Transpose(Y(x))
For i = 1 To UBound(Y(x))
Z(Y(x)(i)) = ""
Next
Y(x + 2) = Application.Transpose(Z.KEYS)
Z.RemoveAll
Next
For x = 3 To 4
For i = 2 To UBound(Y(x))
If Z(Y(x)(i, 1)) = "" Then
Y(5) = Y(5) & Y(x)(i, 1) & "|"
Z(Y(x)(i, 1)) = Z(Y(x)(i, 1)) + 1
Else
Y(6) = Y(6) & Y(x)(i, 1) & "|"
Y(5) = Replace(Y(5), Y(x)(i, 1) & "|", "")
End If
Next
Next
Y(6) = Application.Transpose(Split(Y(6), "|"))
Y(5) = Application.Transpose(Split(Y(5), "|"))
Workbooks.Add
[A1].Resize(, 2) = Array("相同", "不同")
[A2].Resize(UBound(Y(6)), 1) = Y(6)
[B2].Resize(UBound(Y(5)), 1) = Y(5)
End Sub作者: Andy2483 時間: 2022-10-20 13:17
謝謝各位前輩提供這麼多知識在論壇上
今天後學練習到要注意執行效能!
心得註解如下!請各位前輩指正並指導!謝謝!
Option Explicit
Sub TEST_2()
Dim i&, x&, Y, Z, Arr, Brr, Crr, T
'↑宣告變數
T = Timer
Set Y = CreateObject("Scripting.Dictionary")
Set Z = CreateObject("Scripting.Dictionary")
'↑令Y,Z各是字典
For x = 1 To 2
'↑設外順迴圈把兩表資料 用Z字典整理 為不重複並各將Z字典轉置為陣列
',再裝入字典成為Y(3), Y(4)
Y(x) = Sheets(x).Range("A1:A" & Sheets(x).[A65536].End(3).Row)
Y(x) = Application.Transpose(Y(x))
'↑盡量不用轉置的方式處理資料!一兩次還好!多次耗時!
Crr = Y(x)
'↑需要用Crr將字典裡的陣列盛裝出來執行比較快
For i = 1 To UBound(Crr)
Z(Crr(i)) = ""
Next
Y(x + 2) = Application.Transpose(Z.KEYS)
'↑盡量不用轉置的方式處理資料!一兩次還好!多次耗時!
Z.RemoveAll
Next
For x = 3 To 4
'↑設外順迴圈把兩陣列資料分類並組成字串
Crr = Y(x)
'↑需要用Crr將字典裡的陣列盛裝出來執行比較快
For i = 2 To UBound(Crr)
If Z(Crr(i, 1)) = "" Then
Arr = Arr & Crr(i, 1) & "|"
Z(Crr(i, 1)) = Z(Crr(i, 1)) + 1
Else
Brr = Brr & Crr(i, 1) & "|"
Arr = Replace(Arr, Crr(i, 1) & "|", "")
End If
Next
Next
Brr = Application.Transpose(Split(Brr, "|"))
Arr = Application.Transpose(Split(Arr, "|"))
'↑將Arr,Brr字串 用"|" 符號拆解為一維陣列,並轉置為結果
'因為Arr,Brr宣告沒有指定是什麼類型資料!所以可以變換類型!
With Sheets(3)
.[I1].Resize(, 2) = Array("相同", "不同")
.[I2].Resize(UBound(Brr), 1) = Brr
.[J2].Resize(UBound(Arr), 1) = Arr
End With
Set Y = Nothing
Set Z = Nothing
Set Arr = Nothing
Set Brr = Nothing
Set Crr = Nothing
MsgBox Timer - T & "秒"
End Sub