如何在 VBA 中在同一值旁边输出相同类型的值?
continue
I want to use VBA to get the values of columns A and B and output them to columns C and D as below.
- Same names in column A are made into one and output to column C.
- Same values in column B are kept as one and output side by side in column D.
A | B | C | D |
---|---|---|---|
Suzuki | 123 | Suzuki | 123, 456 |
Suzuki | 456 | Kato | 789 |
Suzuki | 456 | SAto | 100 |
Kato | 789 | ||
Kato | 789 | ||
SAto | 100 |
I'm able to get the same value to one with researching on the internet.
However, I'm unable to output the values in column B side by side.
Here is the code I made myself to combine the same values into one.
Please let me know if you can modify my code or if you have a better way to write the code.
VBA
Sub sample()
Dim Dic, i As Integer, name As String
Dim order_number As Long
Set Dic = CreateObject("Scripting.Dictionary") 'Key(キー)とItem(データ)をセットで格納して、リストなどを作成するときに使用。Pythonでいうところのたぶん辞書型
On Error Resume Next
For i = 1 To 10
name = Cells(i, 1).Value '荷受人の列の名前を1つずつ取得
order_number = Cells(i, 2).Value '注文番号を1つずつ取得
Dic.Add name, order_number ' Dicに追加していく
Next i
' 出力
For i = 0 To Dic.Count - 1
mykeys = Dic.Keys
myItems = Dic.Items
Range("C" & i + 1).Value = mykeys(i)
Range("D" & i + 1).Value = myItems(i)
'オブジェクトを開放する
Set Dic = Nothing
Next i
End Sub
↓ My code output
A | B | C | D |
---|---|---|---|
Suzuki | 123 | Suzuki | 123 |
Suzuki | 456 | Kato | 789 |
Suzuki | 456 | Sato | 100 |
Kato | 789 | ||
Kato | 789 | ||
Sato | 100 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只能在字典上调用
Add
- 您需要检查字典是否已经将name
作为键,并且Add
新密钥或更新现有值。试试这个:
You only ever call
Add
on the dictionary - you need to check to see if the dictionary already hasname
as a key, and eitherAdd
a new key or update the existing value.Try this:
结束子
End Sub