【发布时间】:2018-04-19 21:07:24
【问题描述】:
我正在使用 Dictionary 来存储数据,然后将它们转储到另一个工作表中。基本上我有这种格式的数据:
abc 12367
abe 23456
abe 34567
dfy 78890
我需要这样输出:
abc 12367
abe 23456, 34567
dfy 78890
这是存储和输出数据的代码:
Function ReadDict(ByVal wb_name As String, ByVal ws_name As String, row_begin As Integer, row_end As Integer, col As Integer) As Dictionary
On Error Resume Next
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim dictStorage As New Dictionary
Set wbSource = Workbooks(wb_name)
If wbSource Is Nothing Then
Set wbSource = Workbooks.Open(wb_name)
End If
Dim iRowCounter As Integer
Dim vKey, vItem As Variant
For iRowCounter = row_begin To row_end
vKey = wbSource.Sheets(ws_name).Cells(iRowCounter, col).Value
vItem = wbSource.Sheets(ws_name).Cells(iRowCounter, col + 1).Value
If dictStorage.Exists(vKey) = False Then
dictStorage.Add vKey, vItem
Else
dictStorage.item(vKey) = dictStorage.item(vKey) & ", " & vItem
End If
Next iRowCounter
Set ReadDict = dictStorage
End Function
我很确定这是可行的,因为我可以 Debug.Print。
写函数:
Function WriteDict(ByVal wb_name As String, ByVal ws_name As String, row_begin As Integer, col As Integer, dict As Dictionary)
On Error Resume Next
If dict.Count <= 0 Then MsgBox ("Dictionary contains no item!")
Dim wbSource As Workbook
Dim wsSource As Worksheet
Set wbSource = Workbooks(wb_name)
If wbSource Is Nothing Then
Set wbSource = Workbooks.Open(wb_name)
End If
With Worksheets(ws_name)
Dim ky As Variant
With dict
Range(Cells(2, 1), Cells(2 + .Count, 1)).Value = Application.Transpose(.Keys)
Range(Cells(2, 2), Cells(2 + .Count, 2)).Value = Application.Transpose(.Items)
End With
End With
Set dict = Nothing
End Function
函数只写键,不写项目。为什么?我很高兴这些项目在那里,因为我可以简单地 Debug.Print 它们。最令人沮丧的是,如果某些行没有被读取,write 函数可以正常工作,但我发誓这些行没有什么特别的......
我列出了主要的子:
Sub CombineTJ()
Application.ScreenUpdating = False
Dim sSourceWB, sSourceWS, sTargetWS As String
Dim dictTJ As New Dictionary
sSourceWS = ActiveSheet.Name
sTargetWS = "Target"
sSourceWB = ActiveWorkbook.Name
Sheets.Add
ActiveSheet.Name = sTargetWS
Set dictTJ = ReadTJDict(sSourceWB, sSourceWS, 2, 8442, 1)
Call WriteTJDict(sSourceWB, sTargetWS, 2, 1, dictTJ)
Application.ScreenUpdating = True
End Sub
如果 ReadTJDict() 没有读取第 1950 行和第 2000 行之间的某些行,我很确定它可以正常工作,但没有什么特别之处。
【问题讨论】:
-
(简而言之,我将在工作表中将项目所在的列称为 items-column。) 你是说当前(不正确)输出是 items-column 是空白的,还是用键值填充?我假设代码没有抛出任何错误,因为你没有提到任何错误。
-
@Mistella 嗨,我找到了原因,似乎字典的一项长度超过 255 个字符并导致问题。它只显示键,而不是项目。