VBA - 拆分单元格值并将其放入下面的行中

时间:2016-07-14 09:42:03

标签: vba excel-vba excel

我正在寻找一个代码,它会在“:”之后拆分最后一行的单元格,如下所示:

enter image description here

enter image description here

到目前为止,分割数据看起来像这样 - 但它只适用于第一个单元格:

Sub test()
Dim ws As Worksheet
Set ws = Sheets("Sheet3")
Dim fullstring As String, colonposition As Integer, j As Integer, LastRow As Long, FirstRow As Long
Dim lRow As Long, lCol As Long
lRow = Cells(Rows.Count, 1).End(xlUp).Row
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
    For j = 1 To 3
    fullstring = Cells(lRow, lCol).Value
    colonposition = InStr(fullstring, ":")
    Cells(lRow, j).Value = Left(fullstring, colonposition - 1)
    lRow = lRow + 1
    Cells(lRow, j).Value = Mid(fullstring, colonposition + 1)
    Next

End Sub

我发现了类似的问题(有答案)here,但无法将其仅应用于最后一行

任何建议都赞赏!

2 个答案:

答案 0 :(得分:1)

我更喜欢对每个语句使用Range方法,如下所示:

Sub test()
    Dim ws As Worksheet
    Set ws = Sheets("Sheet3")
    Dim actualRange As Range
    For Each actualRange In ws.Range(ws.Cells(ws.Rows.Count, 1).End(xlUp), ws.Cells(ws.Rows.Count, 1).End(xlUp).End(xlToRight))
        actualRange.Offset(-1, 0).Value = Split(actualRange.Value, ":")(0)
        actualRange.Offset(0, 0).Value = Split(actualRange.Value, ":")(1)
    Next
End Sub

答案 1 :(得分:0)

如果有人对@Ondrej讨论的答案感兴趣,这里有两个代码,第一个是静态的,第二个是动态的:

Sub test()
Dim ws As Worksheet
Set ws = Sheets("Sheet1")
Dim actualRange As Range
For Each actualRange In ws.Range(ws.Cells(ws.Rows.Count, 1).End(xlUp), ws.Cells(ws.Rows.Count, 1).End(xlUp).End(xlToRight))
If InStr(Trim(actualRange), ":") > 0 Then
actualRange.Offset(1, 0).Value = Split(actualRange.Value, ":")(1)
actualRange.Offset(0, 0).Value = Split(actualRange.Value, ":")(0)

End If
Next
End Sub

&安培;

Sub test()
Dim ws As Worksheet
Set ws = Sheets("Sheet1")
Dim actualRange As Range
Dim tmpString As String
For Each actualRange In ws.Range(ws.Cells(ws.Rows.Count, 1).End(xlUp), ws.Cells(ws.Rows.Count, 1).End(xlUp).End(xlToRight))
tmpString = actualRange.Value
If InStr(Trim(tmpString), ":") > 0 Then
actualRange.Offset(0, 0).Value = Split(tmpString, ":")(0)

actualRange.Offset(1, 0).Value = Split(tmpString, ":")(1)

End If
Next
End Sub