您可以在 Excel VBA 中执行此操作。如果您之前没有在 Excel 中使用过 VBA,请参阅下面的链接以了解如何访问它。
http://msdn.microsoft.com/en-us/library/ee814737.aspx
确保在尝试任何操作之前备份电子表格,以防出现问题!
我写了一些东西,将数据从你的辅助工作表复制到你的主工作表中。只需打开 VBA 编辑器,然后粘贴代码。
接下来,编辑该ConsolidateWorksheets()
函数,使其具有适合您工作表的名称。如果您有其他工作表,请声明它们并添加另一行来调用ProcessWorksheet
所添加工作表的子例程。
此代码会在找到匹配的 ID 时将您的门票和捐赠工作表中的数据复制到您的主工作表中。如果没有匹配的 id,它不会为该行复制任何内容。
Option Explicit
Sub ConsolidateWorksheets()
'declare the worksheets you are using
Dim mainWks As Worksheet
Dim ticketsWks As Worksheet
Dim donationsWks As Worksheet
'set the worksheet names
Set mainWks = ThisWorkbook.Worksheets("Sheet1")
Set ticketsWks = ThisWorkbook.Worksheets("Sheet2")
Set donationsWks = ThisWorkbook.Worksheets("Sheet3")
Call ProcessWorksheet(mainWks, ticketsWks)
Call ProcessWorksheet(mainWks, donationsWks)
End Sub
' copies data from the otherWks to the mainWks
Sub ProcessWorksheet(mainWks As Worksheet, otherWks As Worksheet)
Dim i As Integer
Dim rowId As Integer
Dim otherRowIndex As Integer
Dim otherLastColIndex As Integer
Dim lastRowIndex As Integer
Dim pasteColStart As Integer
Dim pasteColEnd As Integer
' figure out the last row in the main sheet
lastRowIndex = mainWks.UsedRange.Rows.count
otherLastColIndex = otherWks.UsedRange.Columns.count
' figure out where to copy and paste from
' this assumes that the id row is always the first row in every sheet
pasteColStart = mainWks.UsedRange.Columns.count + 1
pasteColEnd = pasteColStart + (otherLastColIndex - 2)
' copy column headers
otherWks.Activate
otherWks.Range(Cells(1, 2), Cells(1, otherLastColIndex)).Copy
mainWks.Activate
mainWks.Range(Cells(1, pasteColStart), Cells(1, pasteColEnd)).PasteSpecial
' loop through all the rows of the main sheet
For i = 2 To lastRowIndex
' get row id from first cell in current row
rowId = Cells(i, 1).Value
'lookup row id in other worksheets
otherRowIndex = FindIdRowInWks(otherWks, rowId)
If otherRowIndex <> 0 Then
otherWks.Activate
otherWks.Range(Cells(otherRowIndex, 2), Cells(otherRowIndex, otherLastColIndex)).Copy
mainWks.Activate
mainWks.Range(Cells(i, pasteColStart), Cells(i, pasteColEnd)).PasteSpecial
End If
Next i
End Sub
' loops through the given worksheet, looks for a given id in the first column
' and returns the row index where the id was found. returns 0 if nothing found.
Public Function FindIdRowInWks(wks As Worksheet, idToFind As Integer) As Integer
Dim lastRow As Integer
lastRow = wks.Range("A" & Rows.count).End(xlUp).Row
Dim rowNumber As Integer
rowNumber = 0
Dim i As Integer
For i = 2 To lastRow
If (Cells(i, 1).Value = idToFind) Then
rowNumber = i
End If
Next i
FindIdRowInWks = rowNumber
End Function
希望有帮助!