Excel VBA-返回分隔的数据

Excel VBA-返回分隔的数据,excel,vba,Excel,Vba,我是VBA新手。有人能帮我吗?我在单元格A2和A3中有“返回/输入”分隔数据,在B、C和D列中有相应数据。是否可以使用Excel VBA获得图像中所需的结果 如果您希望结果出现在Sheet2中,则此代码将执行您期望的操作,它将检查Sheet1上的列数,并将所有列复制到Sheet2中: Sub foo() Dim LastRow As Long Dim LastCol As Long Dim ws As Worksheet: Set ws = Sheets("Sheet1") 'change th

我是VBA新手。有人能帮我吗?我在单元格A2和A3中有“返回/输入”分隔数据,在B、C和D列中有相应数据。是否可以使用Excel VBA获得图像中所需的结果


如果您希望结果出现在Sheet2中,则此代码将执行您期望的操作,它将检查Sheet1上的列数,并将所有列复制到Sheet2中:

Sub foo()
Dim LastRow As Long
Dim LastCol As Long
Dim ws As Worksheet: Set ws = Sheets("Sheet1") 'change this to the name of your worksheet
Dim ws2 As Worksheet: Set ws2 = Sheets("Sheet2")
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row 'get the last row
LastCol = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column 'get the number of columns from row 2
For i = 2 To LastRow
strTest = ws.Cells(i, 1)
Myarray = Split(strTest, Chr(10)) 'split the values on the first column into an array
    For x = LBound(Myarray) To UBound(Myarray) ' loop through array
        LastRow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row 'get the last row of Sheet2
        ws2.Cells(LastRow2 + 1, 1).Value = Myarray(x) 'paste the contents into Sheet2
        For y = 2 To LastCol 'loop for the number of columns on Sheet1
            ws2.Cells(LastRow2 + 1, y).Value = ws.Cells(i, y) 'paste all relevant columns into Sheet2
        Next y
    Next x
Next i
End Sub

非常感谢您的帮助@Xabier。代码运行得很好。@Navneet我已经更新了我的答案,以复制您在Sheet1上有多少列,如果这有助于您将我的回答标记为答案吗?谢谢。非常感谢:)