[英]Excel - VBA Question. Need to access data from all excel files in a directory without opening the files
因此,我有一个“主” excel文件,需要用目录中excel文件中的数据填充。 我只需要访问每个文件,然后从每个工作簿的第二张表中复制一行,然后将其粘贴到我的主文件中,而无需打开excel文件。
我不是专家,但是我可以处理一些中间宏。 我需要的最重要的事情是无需打开文件就可以逐个访问每个文件。 我真的需要这个,所以我们将不胜感激! 谢谢!
编辑...
因此,我一直试图使用dir函数通过循环遍历目录,但是我不知道如何从第一个文件继续前进。 我在站点上看到了此消息,但对我而言,循环不会停止,它只会访问目录中的第一个文件。
Folder = "\\Drcs8570168\shasad\Test"
wbname = Dir(Folder & "\" & "*.xls")
Do While wbname <> ""
i = i + 1
ReDim Preserve wblist(1 To i)
wblist(i) = wbname
wbname = Dir(FolderName & "\" & "*.xls")
wbname如何下移文件列表?
您不必打开文件(ADO可能是一种选择,如创建的代码链接,或使用ExecuteExcel4Macro),但通常与代码打开文件是最灵活和最简单的方法。
但是,为什么不打开文件-这真的是一个硬约束吗?
我在Macro中的代码循环遍历放置在两个命名工作表之间的所有工作表,并将其数据复制到统一文件中,从而将文件夹中每个工作簿中所有工作表的所有数据收集到一起(通过在后台打开文件)。
如果您对此过程感到满意,则可以轻松地将其定制为仅位于工作表2的X行
我只想指出:您严格不需要VBA从封闭的工作簿中获取值。 您可以使用以下公式:
='C:\MyPath\[MyBook.xls]Sheet1'!$A$3
您也可以在VBA中实现此方法:
Dim rngDestinationCell As Range
Dim rngSourceCell As Range
Dim xlsPath As String
Dim xlsFilename As String
Dim sourceSheetName As String
Set rngDestinationCell = Cells(3,1) ' or Range("A3")
Set rngSourceCell = Cells(3,1)
xlsPath = "C:\MyPath"
xlsFilename = "MyBook.xls"
sourceSheetName = "Sheet1"
rngDestinationCell.Formula = "=" _
& "'" & xlsPath & "\[" & xlsFilename & "]" & sourceSheetName & "'!" _
& rngSourceCell.Address
其他答案也提供了很好的解决方案,也许比这更优雅。
我的Excel类包装器中的一些内容:
Dim wb As Excel.Workbook
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
xlApp.DisplayAlerts = False ''# prevents dialog boxes
xlApp.ScreenUpdating = False ''# prevents showing up
xlApp.EnableEvents = False ''# prevents all internal events even being fired
''# start your "reading from the files"-loop here
Set wb = xlApp.Workbooks.Add(sFilename) '' better than open, because it can read from files that are in use
''# read the cells you need...
''# [....]
wb.Close SaveChanges:=False ''# clean up workbook
''# end your "reading from the files"-loop here
''# after your're done with all files, properly clean up:
xlApp.Quit
Set xlApp = Nothing
祝好运!
brettdj和paulsm4的答案提供了很多信息,但我仍然想加2美分 。
当iDevlop在此线程中回答( 通过VBA从另一个工作簿复制数据 )时,您也可以使用GetInfoFromClosedFile() 。
在宏的开头添加
Application.ScreenUpdating = false
然后在最后
Application.ScreenUpdating = True
并且在宏执行其功能时您不会看到任何文件打开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.