未经测试,但试试这个:
Sub Tester()
Dim lRw As Long, rw As Long, wsSrc As Worksheet, wsDest As Worksheet
Dim cDest As Range, v, v2, k
Set wsSrc = ThisWorkbook.Sheets("Sheet1") 'or activeworkbook
Set wsDest = ThisWorkbook.Sheets("Sheet2")
'next empty row on destination sheet (in "key" column, but offsetting to A))
Set cDest = wsDest.Cells(Rows.Count, 3).End(xlUp).Offset(1, -2)
k = wsSrc.Range("B1").Value 'key value
lRw = wsSrc.Cells(Rows.Count, "A").End(xlUp).Row 'last row of source data
For rw = 3 To lRw
v = wsSrc.Cells(rw, 1).Value
v2 = wsSrc.Cells(rw, 2).Value
If Len(v) > 0 Or Len(v2) > 0 Then 'if either cell has a value
cDest.Value = v 'write values
cDest.Offset(0, 1).Value = v2
cDest.Offset(0, 2).Value = k 'write key
Set cDest = cDest.Offset(1, 0) 'next destination row
End If
Next rw
End Sub
已编辑 - 对于任何指定数量的源列:
Sub Tester()
Const NUM_COLS As Long = 3 'or whatever
Dim lRw As Long, rw As Long, wsSrc As Worksheet, wsDest As Worksheet
Dim cDest As Range, k
Set wsSrc = ThisWorkbook.Sheets("Sheet1") 'or activeworkbook
Set wsDest = ThisWorkbook.Sheets("Sheet2")
'next empty row on destination sheet (in "key" column, but offsetting to A))
Set cDest = wsDest.Cells(Rows.Count, NUM_COLS + 1).End(xlUp).Offset(1, -NUM_COLS)
k = wsSrc.Range("B1").Value 'key value
lRw = wsSrc.Cells(Rows.Count, "A").End(xlUp).Row 'last row of source data
For rw = 3 To lRw 'loop over source rows
With wsSrc.Cells(rw, 1).Resize(1, NUM_COLS)
If Application.CountA(.Cells) > 0 Then 'if any cell has a value
cDest.Resize(1, NUM_COLS).Value = .Value 'write values
cDest.Offset(0, NUM_COLS).Value = k 'write key
Set cDest = cDest.Offset(1, 0) 'next destination row
End If
End With
Next rw
End Sub