我在工作表1中有一张表,其中一列“ G”允许多个值之间用逗号分隔,例如12,24,72。在工作表2中,我想读取表或工作表1并使用选择列C和G写入新记录(行)。如果在G中标识了逗号,则工作表1我希望它为工作表2中的每个实例创建一个新行。
Worksheet1
ID(A) | Name(C) | Period(G)
1 | Paul | 12
2 | Sam | 12,14,72
3 | Karen | 36
Worksheet2
Paul | 12
Sam | 12
Sam | 14
Sam | 72
Karen | 36
答案 0 :(得分:0)
尝试以下代码(注释在代码中):
Option Explicit
Sub FillWS()
Dim ws1 As Worksheet, ws2 As Worksheet
' Set references to worksheets
Set ws1 = Worksheets("Worksheet1")
Set ws2 = Worksheets("Worksheet2")
' Determine last row in column C in worksheet1
Dim lastRow As Long
lastRow = ws1.Cells(ws1.Rows.Count, 3).End(xlUp).Row
Dim i As Long, j As Long, currentRow As Long, name As String, period() As String
currentRow = 1
' Loop through first worksheet
For i = 1 To lastRow
name = ws1.Cells(i, 3).Value
period = Split(ws1.Cells(i, 7).Value, ",")
For j = LBound(period) To UBound(period)
ws2.Cells(currentRow, 1) = name
ws2.Cells(currentRow, 2) = period(j)
currentRow = currentRow + 1
Next
Next
End Sub