嗯,我已经解决了你的第一个问题,直到明天我才能解决第二个问题,如果到那时没有人这样做,我有一个想法。 编辑:请参阅下面的编辑,我保证我会回来 :)
Sub findParent()
Dim masterWs As New Worksheet
Dim masterEndRc As Long
Set masterWs = Sheets("Sheet1")
Dim parentWs As New Worksheet
Set parentWs = Sheets("Sheet2")
Dim masterCounter As Long
Dim parentCounter As Long
parentCounter = 1
masterCounter = 1
Dim colBStr As String 'set up temp variables, you could compare values directly
Dim colCstr As String 'but call me crazy, i think that this way is more accurate
masterEndRc = masterWs.UsedRange.Rows.Count
Do
colBStr = masterWs.Cells(masterCounter, "B").Value 'Load the value into the temp variables
colCstr = masterWs.Cells(masterCounter, "C").Value
If colBStr = colCstr Then
masterWs.Cells(masterCounter, "B").EntireRow.Cut parentWs.Cells(parentCounter, "A")
parentWs.Cells(parentCounter, "E").Value = masterCounter 'Make this the first empty column, this is so that we can find its original row
'for reinsert later
parentCounter = parentCounter + 1
End If
masterCounter = masterCounter + 1
Loop While masterCounter <= masterEndRc
End Sub
编辑
好的,第二个问题解决了 :) 确保更改任何变量以匹配您的工作表,例如列和工作表名称。运行上面宏下的第一个子程序,然后运行下面的第二个子程序。
Sub restoreParent()
Dim masterWs As New Worksheet
Dim masterEndRc As Long
Set masterWs = Sheets("Sheet1")
Dim parentWs As New Worksheet
Set parentWs = Sheets("Sheet2")
Dim parentEndRc As Long
Dim parentCounter As Long
Dim oldRowLong As Long
Dim rowColl As New Collection 'for storing of the parent row numbers for use while changing child rows later
parentEndRc = parentWs.UsedRange.Rows.Count
parentCounter = 1
Do
oldRowLong = parentWs.Cells(parentCounter, "E").Value
rowColl.Add oldRowLong
parentWs.Cells(parentCounter, "B").EntireRow.Cut masterWs.Cells(oldRowLong, "A")
parentCounter = parentCounter + 1
Loop While parentCounter <= parentEndRc
changeChildRows rowColl, masterWs
End Sub
Function changeChildRows(rowColl As Collection, masterWs As Worksheet)
Dim nextChildRow As Long
Dim childRowCounter As Long
Dim parentRow As Variant
Dim firstChild As Boolean
firstChild = True
For Each parentRow In rowColl
childRowCounter = parentRow
Do
If firstChild = True Then
nextChildRow = parentRow + 1
If masterWs.Cells(parentRow, "C").Value = masterWs.Cells(nextChildRow, "C") Then
masterWs.Cells(nextChildRow, "D").Value = masterWs.Cells(parentRow, "D").Value 'Make sure to change these column values to match yours
End If
firstChild = False
ElseIf firstChild = False Then
nextChildRow = nextChildRow + 1
If masterWs.Cells(parentRow, "C").Value = masterWs.Cells(nextChildRow, "C") Then
masterWs.Cells(nextChildRow, "D").Value = masterWs.Cells(parentRow, "D").Value 'Make sure to change these column values to match yours
End If
End If
childRowCounter = childRowCounter + 1
Loop Until masterWs.Cells(childRowCounter, "C").Value <> masterWs.Cells(parentRow, "C").Value
firstChild = True
Next parentRow
End Function