我怎樣才能像這樣轉換兩列
A B
foo foo1
foo foo2
foo foo3
faa faa1
faa faa2
fee fee1
fee fee2
在以下結構中
foo
foo1,foo2,foo3
faa
faa1,faa2
fee
fee1,fee2
到目前為止,我試圖做的是創建我的回圈。
Sub DowithIf()
rw = 11
cl = 2
erw = 1000
Do While rw < erw
rw = rw 1
Loop
End Sub
但我不知道的第一件事是檢測 A 列的第一個值(foo)與 A 列的第二個值(foo)相同。如果值是新的,則遍歷 A 列,將其保存在上面的代碼中,并將值保存在 B 列中,A2 是否等于 A1 如果是,則保存 foo2,A3 是否等于 A4,是的,保存 foo3,A4 是否等于 A3 否,然后是新值...
編輯:

uj5u.com熱心網友回復:
你首先必須知道一個問題必須包含一段代碼,即使它不能按你的需要作業。然后,經常檢查您的問題并回答澄清問題也很好。現在,跳到你理解我的觀點,我做了一個例外,并嘗試展示一段能夠做你需要的(我理解的)代碼。它應該非常快,使用陣列和 a Dictionary:
Sub processTwoColumns()
Dim sh As Worksheet, lastR As Long, arr, arrFin2C, arrfinUnique
Dim i As Long, k As Long, dict As Object
Set sh = ActiveSheet 'use here the sheet you need
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row 'last row on A:A column
arr = sh.Range("A1:B" & lastR).value 'place the range to be processed in an array, for faster iteration
ReDim arrFin2C(1 To UBound(arr), 1 To 1) 'reDim the array to keep first way of returning
Set dict = CreateObject("Scripting.Dictionary") 'Set the Scripting Dictionary object
For i = 1 To UBound(arr) 'iterate between the array rows
arrFin2C(i, 1) = arr(i, 1) & " " & arr(i, 2) ' building the array to be return, by concatenation of the two columns
dict(arr(i, 1)) = dict(arr(i, 1)) & ", " & arr(i, 2)'place in a dictionary unique keys and items separated by ", "
Next i
sh.Range("D1:D" & lastR).value = arrFin2C 'drop the array content
ReDim arrfinUnique(1 To dict.count * 2, 1 To 1): k = 1 'reDim the array necessary to keep the processed result for the second way
For i = 1 To dict.count - 1 'iterate between the dictionary keys/items
arrfinUnique(k, 1) = dict.Keys()(i): k = k 1 'place in the array the dictionary key
arrfinUnique(k, 1) = Mid(dict.items()(i), 3): k = k 1 'place in the array the dictionary item (without leading ", ")
Next i
sh.Range("F2").Resize(UBound(arrfinUnique), 1).value = arrfinUnique 'drop the array content
End Sub
上面的代碼將在“D:D”列中回傳第一個所需版本,從第一行開始,在“F:F”中回傳第二個,從第二行開始。該代碼可以很容易地適應在任何其他地方/表中回傳......
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437779.html
標籤:vba
上一篇:我是VBA新手,可以使用一些幫助。代碼突然停止作業Range類的運行時錯誤“1004”PasteSpecial方法失敗
