我正在读取一些组织如下的数据: (将|解释为细胞分裂) 属性|价值|单位| [空] |属性|价值|单位| [空] ... 我将这些数据放入一个集合中,然后在Sub的末尾打印该集合。
一些背景: 并不总是有单位,但是如果它们存在,我希望它们串联到值上。 也不总是有值,当发生这种情况时,我想跳到下一个属性,而不是记录没有值的属性。
Dim coll As New Collection
While j <= FinalColumn
'Check if the attribute actually has a value
If Len(Cells(row, (j + 1)).Value) <> 0 Then
coll.Add Cells(row, j).Value 'add attribute
Dim val As Variant
If Len(Cells(row, (j + 2)).Value) <> 0 Then
val = Cells(row, (j + 1)).Value & " " & Cells(row, j + 2).Value 'add value with units
Else
val = Cells(row, (j + 1)).Value 'add just the value if there are no units
End If
coll.Add val 'add value to collection
End If
j = j + 4 'move on to next attribute
Wend
我希望打印的行看起来像这样:
[属性]
[值]
[属性]
[值]
...
但是,相反,我得到的是这样的东西:
[属性]
[值]
[属性]
(空白)
[属性]
[值]
(空白)
[属性]
...
是否注意到空格?看起来好像与值不存在时向集合中添加内容有关,但我无法弄清楚哪里出了错。
答案 0 :(得分:0)
在检查条目时,最好包括Trim()
:
Dim coll As New Collection, v , u, ws As Worksheet
Set ws = ActiveSheet
While j <= FinalColumn
v = Trim(ws.Cells(row, j + 1).Value)
u = Trim(ws.Cells(row, j + 2).Value)
'Check if the attribute actually has a value/unit
If Len(v) > 0 Then
coll.Add ws.Cells(row, j).Value 'add attribute
If Len(u) > 0 Then v = v & " " & u
coll.Add v 'add value to collection
End If
j = j + 4 'move on to next attribute
Wend