这个问题似乎被多次提出,但我有一些麻烦。该任务在列中给出了一些单元格(比如它的列A)在每个单元格中分割文本(分隔符是空格"")并在另一列中打印所有获得的单词(比如列C) )。
在阅读了一些答案之后,我写了以下代码:
Sub splitting()
Dim tmp As Collection
Dim i As Integer, j As Integer
For i = 0 To 3
tmp.Add split(Cells(i + 1, 1).Value, " ")
Next i
For j = 0 To tmp.Count
Cells(j + 1, 3).Value = tmp(j)
Next j
End Sub
这里我使用集合代替数组来具有动态重新排列的能力(每次在循环中添加新项目)。我还假设文本仅在前四行中进行测试。
它给了我一个错误
运行时错误' 91':对象变量或With块变量未设置
我做错了什么,我应该如何正确地做到这一点?
答案 0 :(得分:2)
总结评论中提到的所有问题,请参阅以下示例:
输入:
one two three four five
six seven eight nine
ten eleven twelve
Sub splitting()
Dim tmp As Collection
Dim i As Integer, j As Integer, k As Integer
Set tmp = New Collection
For i = 1 To 3
tmp.Add Split(Cells(i, 1).Value, " ")
Next i
For j = 1 To tmp.Count
For k = 0 To UBound(tmp(j))
Debug.Print tmp(j)(k)
Next k
Next j
End Sub
输出:
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
答案 1 :(得分:-2)
您的集合已声明但尚未初始化。尝试更改为:
Dim tmp As New Collection