簡體   English   中英

Excel-VBA問題。 需要訪問目錄中所有Excel文件中的數據而無需打開文件

[英]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),但通常與代碼打開文件是最靈活和最簡單的方法。

  1. 從封閉的工作簿(ADO)復制范圍
  2. ExecuteExcel4Macro
  3. 鏈接方法

但是,為什么不打開文件-這真的是一個硬約束嗎?

我在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

祝好運!

brettdjpaulsm4的答案提供了很多信息,但我仍然想加2美分

iDevlop在此線程中回答( 通過VBA從另一個工作簿復制數據 )時,您也可以使用GetInfoFromClosedFile()

在宏的開頭添加

Application.ScreenUpdating = false

然后在最后

Application.ScreenUpdating = True

並且在宏執行其功能時您不會看到任何文件打開。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM