[英]Excel VBA Macro to match cell value from workbooks in a root folder then copy specific cell
Picture above is the master workbook.上图是主工作簿。 Can anyone help me to write the vba so it will find workbooks throughout the root folder (eg C:\\Work\\2017) that match with the account number and copy the B9 and E9 cells to the master cell.
任何人都可以帮助我编写 vba,以便它会在整个根文件夹(例如 C:\\Work\\2017)中找到与帐号匹配的工作簿,并将 B9 和 E9 单元格复制到主单元格。 The 2nd picture is a system generated workbook with random name (eg export!-097a0sdk.xls), that's why I need a shortcut to make this task easier.
第二张图片是一个系统生成的工作簿,具有随机名称(例如 export!-097a0sdk.xls),这就是为什么我需要一个快捷方式来使这个任务更容易。
This is the result I expected by using the code这是我使用代码预期的结果
This is the excel generated by system这是系统生成的excel
Thank you谢谢
If I understood correctly then the following will loop through a given directory and it will open and check each file for the required information, if found, it will add the values to your Master workbook.如果我理解正确,那么以下内容将循环遍历给定的目录,它将打开并检查每个文件以获取所需信息,如果找到,它会将值添加到您的主工作簿中。
Note : This code will not open a file if it has "Master" in its filename.注意:如果文件名中包含“Master”,此代码将不会打开文件。
Sub LoopThroughFolder()
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim wb As Workbook
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim myFile As File
Dim AccNumber As String
Dim LastRow As Long, i As Long
Dim sPath As String
sPath = "C:\Work\2017"
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A
Application.DisplayAlerts = False
'do not display alerts
Set myFolder = FSO.GetFolder(sPath) 'set the root folder
For Each myFile In myFolder.Files 'for each file in the folder
If InStr(myFile.Name, "Master") = 0 Then
'if file to open does not have "Master" in it's name then
Set wb = Workbooks.Open(myFile.Path) 'open the file
AccNumber = wb.Sheets(1).Range("B2") 'check for account number on first Sheet
For i = 1 To LastRow 'loop through current Sheet to check if we have a match for the account number
If ws.Cells(i, 1) = AccNumber Then 'if match
ws.Cells(i, 2) = wb.Sheets(1).Range("B9") 'pass the values from the required range
ws.Cells(i, 3) = wb.Sheets(1).Range("E9")
End If
Next i
wb.Close False 'close and do not save changes
Set wb = Nothing
End If
Next
Application.DisplayAlerts = True
End Sub
Also you might have to set a reference to the relevant library to use FileSystemObject
, to do that:此外,您可能必须设置对相关库的引用才能使用
FileSystemObject
,以执行此操作:
How do I use FileSystemObject in VBA? 如何在 VBA 中使用 FileSystemObject?
Within Excel you need to set a reference to the VB script run-time library.在 Excel 中,您需要设置对 VB 脚本运行库的引用。 The relevant file is usually located at
\\Windows\\System32\\scrrun.dll
相关文件通常位于
\\Windows\\System32\\scrrun.dll
Microsoft Scripting Runtime
'Microsoft Scripting Runtime
”旁边的复选框scrrun.dll
file will be displayed below the listbox scrrun.dll
文件的全名和路径将显示在列表框下方
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.