我目前有一個檔案夾,其中包含許多(> 100 個)excel 作業簿。在所有這些作業表上,我只需要 2 個特定的資料單元格,并且需要將它們合并到 1 個主作業表中。我目前正在嘗試創建一個 VBA 腳本,它允許我從每個檔案中復制這兩個特定的單元格,但是在此程序中遇到了一些問題。
我目前有以下腳本:
Sub Macro()
Dim StrFile As String
Dim TargetWb As Workbook
Dim SourceWb As Workbook
Dim i As Integer
Set TargetWb = Workbooks("Practice.xlsm")
i = 2
StrFile = Dir("\\W.X.com\Y\OPERATIONS\Performance-Reporting\SharedDocuments\Regulatory\Z\X")
Do While Len(StrFile) > 0
Set SourceWb = Workbooks.Open(StrFile)
TargetWb.Sheets("Sheet1").Range("A" & i).Value = SourceWb.Sheets("SCR").cell("C24").Value
TargetWb.Sheets("Sheet1").Range("B" & i).Value = SourceWb.Sheets("SCR").cell("B3").Value
SourceWb.Close SaveChanges:=False
i = i 1
Loop
End Sub
當我運行這個腳本時,絕對沒有任何反應。我不確定為什么會這樣,有人可以幫忙嗎?
我對 VBA 比較陌生,所以如果它是一個非常明顯的修復,我會道歉。
提前致謝!
uj5u.com熱心網友回復:
由于只需要回傳兩個單元格值,因此可以在不打開作業簿的情況下使用ExecuteExcel4Macro
. 請測驗下一個代碼并發送一些反饋:
Sub Macro()
Dim StrFile As String, TargetWb As Workbook, ws As Worksheet, i As Long, StrFormula As String
Const strPath As String = "\\W.X.com\Y\OPERATIONS\Performance-Reporting\SharedDocuments\Regulatory\Z\X\" 'take care of the ending backslash
Set TargetWb = Workbooks("Practice.xlsm")
Set ws = TargetWb.Sheets("Sheet1")
i = 2
StrFile = Dir(strPath & "*.xls*") 'it returns all files having extensions as xls, xlsx, xlsm, xlsa, xlsb
Dim sheetName As String: sheetName = "SCR"
Do While Len(StrFile) > 0
StrFormula = "'" & strPath & "[" & StrFile & "]" & sheetName
ws.Range("A" & i).value = Application.ExecuteExcel4Macro(StrFormula & "'!R24C3")
ws.Range("B" & i).value = Application.ExecuteExcel4Macro(StrFormula & "'!R3C2")
i = i 1
StrFile = Dir() 'needed to continue the iteration up to the last file
Loop
End Sub
uj5u.com熱心網友回復:
如果目標作業表名稱是靜態的,是否需要使用 VBA?外部鏈接是危險的,但通過 VBA 閱讀不再如此。
在一個新檔案中,您可以輸入: ='[File_01.xlsx]sheetname'!$C$24 等 您需要路徑才能在不打開目標檔案的情況下使用它。要生成這些公式,您可以讓單元格包含路徑、檔案名和作業表名。(如果檔案名是序號,只需從第一個向下拖動)如果您命名可以執行的單元格=Concatenate(path,file,sheet)
或者如果不是,則類似=CONCATENATE(,B4,B5,"'!",B6)
INDIRECT 的內容僅適用于打開的目標檔案,因此在某些階段您需要復制和粘貼路徑值,并放在=
前面。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/491504.html