说我在Excel电子表格中有以下数据:
Andy Dick
Brad Penny Paisley
Charlie Daniels Brown Sheen Schwab
Dave Robinson
Evan Longoria
Frank Sinatra Thomas
我需要做的是根据数据中的父子关系减少到两列,如下所示:
Andy Dick
Brad Penny
Brad Paisley
Charlie Daniels
Charlie Brown
Charlie Sheen
Charlie Schwab
Dave Robinson
Evan Longoria
Frank Sinatra
Frank Thomas
我不是一个真正的Excel人,但是我必须要写一个宏,或者说对吗?建议?
答案 0 :(得分:3)
Sub ParentChild()
Dim vaNames As Variant
Dim i As Long, j As Long
Dim aReturn() As String
Dim lCnt As Long
'Fill an array with values
vaNames = Sheet1.Range("A1:E6").Value
'loop through the "rows"
For i = LBound(vaNames, 1) To UBound(vaNames, 1)
'loop through the "cols" starting with 2
For j = LBound(vaNames, 2) + 1 To UBound(vaNames, 2)
'if there's a last name present
If Len(vaNames(i, j)) > 0 Then
'fill a new array with the first and last names
lCnt = lCnt + 1
ReDim Preserve aReturn(1 To 1, 1 To lCnt)
aReturn(1, lCnt) = vaNames(i, LBound(vaNames, 2)) & " " & vaNames(i, j)
End If
Next j
Next i
'write the new array out to a range
Sheet1.Range("A10").Resize(UBound(aReturn, 2), 1).Value = Application.WorksheetFunction.Transpose(aReturn)
End Sub