根据分隔符剪切一个string

我正在尝试为每个循环遍历几千行数据,这些数据都具有这种风格: 1010-2020-3030

我想用连字符作为分隔符将这个string拆分成3个单元格。 我想把1010放入AI电池,2020放入AJ电池,3030放入AK电池。

我搜遍了谷歌,并结合了我发现的几个例子,但我得到一个对象错误1004.这是迄今为止的代码:

 Sub Cell_Loop() Dim cell As Range For Each cell In ActiveSheet.Range("I2:I3000") Selection.TextToColumns _ Destination:=Range("AI" & cell), _ '(I'm trying to use cell as a variable to iterate through.) DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, _ ConsecutiveDelimiter:=False, _ Tab:=True, _ Semicolon:=False, _ Comma:=False, _ Space:=False, _ Other:=True, _ OtherChar:="-" Next cell End Sub 

任何人都可以看到我要去哪里错了?

TextToColumns可以处理列I中所有将近3000个条目,并将它们分发到列AI:AK。

 Sub Split_Without_Loop() With ActiveSheet .Range(.Cells(2, "I"), .Cells(.Rows.Count, "I").End(xlUp)).TextToColumns _ Destination:=Range("AI2"), _ DataType:=xlDelimited, _ Tab:=False, _ Semicolon:=False, _ Comma:=False, _ Space:=False, _ Other:=True, _ OtherChar:="-" End With End Sub 

一些logging的代码可以被清除,因为它不涉及这个操作。

你最初的问题是,你正在循环单元格到代表每个单元格的范围variables,然后使用Selection来pipe理TextToColumns命令。 没有任何select,或者当前选定的单元格不包含连字符,无论如何,您并没有将select更改为循环中正在重复的单元格。 它可能会与cell.TextToColumns _而不是Selection.TextToColumns _但循环会极大地减缓它。

在这里输入图像说明