我在 A 列中有重復資料 我想從 A 列資料中提取到 B 列的唯一值,并在 C 列中獲取 A 列資料重復項的計數
在這里,我發現這個 vba 代碼在資料從沒有標題的 A1 列開始時作業
這里我的問題是什么我有像下面這個例子的標題的資料
Col A1 Fruits Column B1 Fruits Column C1 Dup Count
Apple
Banana
Apple
Orange
Banana
Orange
Apple
我需要像下面這樣的輸出示例
Col A1 Fruits Column B1 Fruits Column C1 Dup Count
Apple Apple 3
Banana Banana 2
Apple Orange 2
Orange
Banana
Orange
Apple
在這里,當我根據我得到的資料運行此 vba 代碼時(運行時錯誤“9”)(下標超出范圍)
這行代碼以黃色突出顯示
dict(arr(i, 1)) = dict(arr(i, 1)) 1
Sub uniqueValues()
Dim sh As Worksheet, lastR As Long, arr, arrFin, i As Long, dict As Object
Set sh = ActiveSheet 'use here the sheet you need
lastR = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
arr = Range("A2:A" & lastR).Value
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To lastR
dict(arr(i, 1)) = dict(arr(i, 1)) 1
Next i
arrFin = Application.Transpose(Array(dict.Keys, dict.items))
sh.Range("B2").Resize(dict.Count, 2).Value = arrFin
End Sub
uj5u.com熱心網友回復:
如果最后一行是(例如)10,那么您的陣列arr大小為(1 到9,1到 1),因此您不能lastR用作For回圈中的限制(僅當資料從 Row1 開始時才有效)-使用For i = 1 To UBound(arr, 1)來代替。
Sub uniqueValues()
Dim sh As Worksheet, lastR As Long, arr, arrFin, i As Long, dict As Object
Set sh = ActiveSheet 'use here the sheet you need
lastR = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
arr = Range("A2:A" & lastR).Value
Set dict = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(arr, 1) '<<<< not `lastR`
dict(arr(i, 1)) = dict(arr(i, 1)) 1
Next i
arrFin = Application.Transpose(Array(dict.Keys, dict.items))
sh.Range("B2").Resize(dict.Count, 2).Value = arrFin
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374116.html
下一篇:ExcelJs動態超鏈接不路由
