我最近發表了一篇關于從一個檔案夾中的多個檔案復制單元格的帖子,并得到了一些很大的幫助。
從 1 個檔案夾中的多個檔案復制單元格
這個答案是完全正確的,但是我需要稍微改變一下。我發了一個新帖子,因為那里的答案確實有效,不確定這是否是正確的程序。
我從中得到的代碼如下所示:
Sub Macro()
Dim StrFile As String, TargetWb As Workbook, ws As Worksheet, i As Long, StrFormula As String
Const strPath As String = "\\pco.X.com\Y\OPERATIONS\X\SharedDocuments\Regulatory\Z\X\" 'take care of the ending backslash
Set TargetWb = Workbooks("X.xlsm")
Set ws = TargetWb.Sheets("Macro")
i = 3
StrFile = Dir(strPath & "*.xls*") 'it returns all files having extensions as xls, xlsx, xlsm, xlsa, xlsb
Dim sheetName As String: sheetName = "S"
Do While Len(StrFile) > 0
StrFormula = "'" & strPath & "[" & StrFile & "]" & sheetName
ws.Range("B" & i).Value = Application.ExecuteExcel4Macro(StrFormula & "'!R24C3")
ws.Range("A" & i).Value = Application.ExecuteExcel4Macro(StrFormula & "'!R3C2")
i = i 1
StrFile = Dir() 'needed to continue the iteration up to the last file
Loop
End Sub
在我從中提取兩個資料點的檔案夾中,實際上有超過 1000 個不同的作業簿。我只需要其中大約 20/30 的資料。最初我打算從這個檔案夾中獲取所有資料,然后快速瀏覽一下以獲得我需要的東西,因為我認為這會更容易。煩人的是,使用宏從這 1000 個檔案中提取會導致 excel 崩潰,所以我需要稍微不同地播放它。
如果檔案名的一部分與主表中的代碼串列匹配,是否可以只從這些檔案中提取資料?
例如,在 B 列中,列出了 20 個代碼“3333”、“44444”、“562872”等,我想從中提取資料的唯一檔案是“ABCD 3333 BDBD”、“AJKP 4444”和“hhhhh 562872 ha” .
請讓我知道這是否清楚,如果您認為可以很容易地做到這一點。
提前致謝!
uj5u.com熱心網友回復:
使用函式 InStr() 和陣列可以解決問題:
Sub Macro()
Dim StrFile As String, TargetWb As Workbook, ws As Worksheet, i As Long, StrFormula As String
Const strPath As String = "\\pco.X.com\Y\OPERATIONS\X\SharedDocuments\Regulatory\Z\X\" 'take care of the ending backslash
'this is the range where the filename codes are. Change as needed
Dim arr_files As Variant: arr_files = ThisWorkbook.Sheets("Master").Range("B2:B20")
Set TargetWb = Workbooks("X.xlsm")
Set ws = TargetWb.Sheets("Macro")
i = 3
StrFile = Dir(strPath & "*.xls*") 'it returns all files having extensions as xls, xlsx, xlsm, xlsa, xlsb
Dim sheetName As String: sheetName = "S"
Do While Len(StrFile) > 0
If Not file_to_process(StrFile, arr_files) Then GoTo skip_file
StrFormula = "'" & strPath & "[" & StrFile & "]" & sheetName
ws.Range("B" & i).Value = Application.ExecuteExcel4Macro(StrFormula & "'!R24C3")
ws.Range("A" & i).Value = Application.ExecuteExcel4Macro(StrFormula & "'!R3C2")
i = i 1
skip_file:
StrFile = Dir() 'needed to continue the iteration up to the last file
Loop
End Sub
Private Function file_to_process(file_name As String, arr_files As Variant) As Boolean
Dim Key As Variant
For Each Key In arr_files
If InStr(1, file_name, Key, vbTextCompare) > 0 Then
file_to_process = True
Exit For
End If
Next Key
End Function
我創建了一個小函式來檢查每個檔案名中每個代碼的每個檔案名,arr_files因此如果一個檔案名在字串中有代碼,將檢查為真并獲取資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/491501.html
下一篇:無法將陣列從多維陣列傳遞給函式
