我借用代码通过回车从一个单元格中拆分文本,并且它运行良好,但它仅适用于活动单元格,并且我有一个大约500行的文档。
我试图实现一个循环函数,但程序只是停止(挂起)。
如何正确实现循环功能或范围功能?
这是我正在使用的代码:
Option Explicit
Private Sub CommandButton1_Click()
On Error Resume Next
Call SplitText
End Sub
Sub SplitText()
Dim str() As String
If Len(ActiveCell.Value) Then ' CHECK IF THE ACTIVE CELL IS NOT EMPTY.
' SPLIT THE ACTIVE CELL'S VALUE WITH LINE FEED (vbLf).
str = VBA.Split(ActiveCell.Value, vbLf)
' REARRANGE TEXT TO MULTIPLE COLUMNS.
ActiveCell.Resize(1, UBound(str) + 1).Offset(0, 1) = str
End If
End Sub
表格如下:
答案 0 :(得分:0)
试试这个:
Option Explicit
Sub SplitText()
Dim str() As String
Dim i As Long
i = 1 ' start at row 1
Do
If Len(Cells(i, "A").Value) Then ' CHECK IF THE ACTIVE CELL IS NOT EMPTY.
str = VBA.Split(Cells(i, "A"), vbLf) ' SPLIT THE ACTIVE CELL'S VALUE WITH LINE FEED (vbLf).
Cells(i, "A").Resize(1, UBound(str) + 1).Offset(0, 1) = str ' REARRANGE TEXT TO MULTIPLE COLUMNS.
End If
i = i + 1
Loop Until IsEmpty(Cells(i, "A")) ' Loop until the first empty row
End Sub
答案 1 :(得分:0)
你可以
SplitText()
以接收范围参数并对其进行操作示例:
Private Sub CommandButton1_Click()
Dim C As Range
On Error Resume Next
' work on each cell within selected range
For Each C In Selection.Cells
SplitText C
Next C
End Sub
Sub SplitText(Target As Range)
Dim str() As String
If Len(Target.Value) Then ' CHECK IF THE ACTIVE CELL IS NOT EMPTY.
' SPLIT THE ACTIVE CELL'S VALUE WITH LINE FEED (vbLf).
str = VBA.Split(Target.Value, vbLf)
' REARRANGE TEXT TO MULTIPLE COLUMNS.
Target.Resize(1, UBound(str) + 1).Offset(0, 1) = str
End If
End Sub
答案 2 :(得分:0)
不清楚您想要循环的范围。你可以轻松地使用这样的东西来遍历范围内的所有单元格:
Sub ProcessCells()
Dim CellRange
'Replace with whatever range you want to iterate over
Set CellRange = Range("C13:F19")
For Each cell In CellRange
cell.Value = 10
Next cell
End Sub
只需在for循环内的单元格上添加要执行的操作,使用单元格引用当前正在处理的单元格,例如
str = VBA.Split(cell.Value, vbLf)