我有一个代码,用于将Excel中的多行单元格拆分成多行,并且它适用于单个单元格。但是,如果我扩展范围(如下所示),则会收到Type Mismatch
错误消息。
Dim SplitText
SplitText = Split(Range("A1:B1").Value, vbLf)
Range("A1:B1").Resize(UBound(SplitText) + 1).Value = Application.Transpose(SplitText)
到目前为止,我没有找到我错过的东西。
答案 0 :(得分:2)
Split
需要一个字符串参数。你必须逐一完成。
尝试类似的事情:
Dim SplitText
Dim myRange As Range, r As Range
Set myRange = Sheet1.Range("A1:B1") '/* change Sheet1 to actual sheet */
For Each r In myRange
SplitText = Split(r, vbLf)
r.Resize(UBound(SplitText) + 1) = Application.Transpose(SplitText)
Next
答案 1 :(得分:0)
以下代码应该适合您,请记住,它还会插入要填充的新行,而不是使用内容填充现有行。如果您不需要,只需删除第一个For Each
循环和行插入语句。
Sub SplitText()
Dim MaxSize As Integer
Dim rng As Range
Set rng = Range("A1:B1")
MaxSize = 0
For Each cell In rng
Dim CurrentSize As Integer
CurrentSize = UBound(Split(cell.Value, vbLf))
If CurrentSize > MaxSize Then
MaxSize = CurrentSize
End If
Next
Rows((rng.Row + 1) & ":" & (rng.Row + MaxSize)).Insert Shift:=xlDown
For Each cell In rng
Dim SplitText
SplitText = Split(cell.Value, vbLf)
cell.Resize(UBound(SplitText) + 1).Value = Application.Transpose(SplitText)
Next
End Sub