我想編寫一個程序,它將兩個單獨的工作簿中的變量名稱匹配,而不是將所有信息從變量複製到從兩個工作簿到新工作的分頁符。每個工作簿都有多個分頁符而不是工作表。 例如:Excel基於變量合併兩個文件
Workbook A (Variable = X)
Persons Name
X Bill
Work Book B
Persons Nickname
X Billy
New Workbook
Page 1
Persons Name
X Bill
Page 2
Persons Nickname
X Billy
我用的是代碼在這個site合併兩個選擇的工作簿,但我無法弄清楚如何通過名字來匹配和比複製到分頁符。任何人都可以有建議,或可以幫助指導我? 謝謝!
代碼: 這是不正確的,但我試圖用一個VLOOKUP找到值中的至少一個工作表中的
MergeSelectedWorkbooks()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim SelectedFiles() As Variant
Dim NRow As Long
Dim FileName As String
Dim NFile As Long
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
Dim VariableX As Variant
' Create a new workbook and set a variable to the first sheet.
Set SummarySheet = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
' Modify this folder path to point to the files you want to use.
FolderPath = "C:\Users\Documents\Test"
' Set the current directory to the the folder path.
ChDrive FolderPath
ChDir FolderPath
SelectedFiles = Application.GetOpenFilename(_
filefilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 1
' Loop through the list of returned file names
For NFile = LBound(SelectedFiles) To UBound(SelectedFiles)
' Set FileName to be the current workbook file name to open.
FileName = SelectedFiles(NFile)
' Open the current workbook.
Set WorkBk = Workbooks.Open(FileName)
' Set the cell in column A to be the file name.
SummarySheet.Range("A" & NRow).Value = FileName
' Set the source range to be A9 through C9.
' Modify this range for your workbooks. It can span multiple rows.
Set SourceRange = VBAVlookup(2, WorkBk.Worksheets(1).Range("A1:A25"), 2, False)
' Set the destination range to start at column B and be the same size as the source range.
Set DestRange = SummarySheet.Range("B" & NRow)
Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
SourceRange.Columns.Count)
' Copy over the values from the source to the destination.
DestRange.Value = SourceRange.Value
' Increase NRow so that we know where to copy data next.
NRow = NRow + DestRange.Rows.Count
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
Next NFile
' Call AutoFit on the destination sheet so that all data is readable.
SummarySheet.Columns.AutoFit
End Sub
Function VBAVlookup(ByVal search As Variant, _
cell_range As Range, _
offset As Long, _
Optional opt As Boolean = False)
Dim result As Variant
result = WorksheetFunction.VLookup(search, cell_range, offset, opt)
'do some cool things to result
VBAVlookup = result
End Function
請向我們展示您的代碼。但也不能保證該鏈接將在未來保持活力,再加上,有可能是在您的副本錯別字,而我們需要看到你做了什麼,試圖通過名字來匹配。 – FreeMan