2016-06-08 242 views
2

編輯:user3561813user3561813之後建議加入"/",現在它讀取第一個文件。我有一個超出範圍的錯誤消息"9"。它會正確讀取第一個文件。最終,我試圖打開每個文件,並閱讀名稱和年齡(這是一個測試不是真正的生產形式)。並將這些值返回到我的主工作表中。Excel VBA:如何打開並從excel文件讀取

enter image description here

原來的問題

我想要的文件夾中讀取的Excel表格百,讀一個特定的細胞位置,並把它們記錄到我的測試工作。我google了這個教程,並試圖寫我的代碼。但是,當我執行獲取文件夾功能時,選擇了一個文件夾路徑,它不循環我有的Excel文件。 (或記錄他們的名字)

'Source: https://www.youtube.com/watch?v=7x1T4s8DVc0 
Sub GettingFolder() 
Dim SelectedFolder As String 

With Application.FileDialog(msoFileDialogFolderPicker) 
    .Title = "Select folder" 
    .ButtonName = "Confirm" 
    .InitialFileName = "U:\" 

    If .Show = -1 Then 
     'ok clicked 
     SelectedFolder = .SelectedItems(1) 
     MsgBox SelectedFolder 
     ' This is where I want to call my function 
     LoopFiles (SelectedFolder) 
    Else 
     'cancel clicked 
    End If 
End With 
End Sub 

' Source: http://www.excel-easy.com/vba/examples/files-in-a-directory.html 
Sub LoopFiles(path As String) 
Dim directory As String, fileName As String, sheet As Worksheet 
Dim i As Integer, j As Integer 

' Avoid Screen flicker and improve performance 
Application.ScreenUpdating = False 
' Fixed per suggestion below.. 
directory = path & "\" 
fileName = Dir(directory & "*.xl??") 

Do While fileName <> "" 
    i = i + 1 
    j = 2 
    Cells(i, 1) = fileName 
    Workbooks.Open (directory & fileName) 
    For Each sheet In Workbooks(fileName).Worksheets 
     Workbooks("Testing.xlsm").Worksheets(1).Cells(i, j).Value = sheet.Name 
     j = j + 1 
    Next sheet 
    Workbooks(fileName).Close 
    fileName = Dir() 
Loop 

' Reset the screen update setting 
Application.ScreenUpdating = True 
End Sub 
+1

如果你解釋「它不允許我執行它」意味着你會大大增加獲得答案的機會。 – SantiBailors

+0

'fileName = Dir(directory&「* .xl ??」)'實際上是否返回一個非空字符串? 'path'參數的值是否以反斜槓結束?你可能想要打印'directory&「* .xl ??」'的結果,以確保它是一個用作'Dir()'參數的值應該返回你期望的值。 – SantiBailors

+0

請注意,在LoopF​​iles中收到的'path'沒有尾部的反斜槓,因此您的'filename = Dir(directory&「* .xl ??」)'不會產生正確的路徑,這意味着Dir會返回一個空字符串 – Dave

回答

1

在你的代碼中,path變量可能不包含斜槓。這會導致你的LoopFiles(<>)子程序下面的代碼是不準確的:

directory = path 
fileName = Dir(directory & "*.xl??") 

文件名看起來是這樣的:c:\users\name\documentshello.xlsx

嘗試更改上面的代碼:

directory = path & "\" 
fileName = Dir(directory & "*.xl??") 

這是否解決問題?

+0

謝謝,這解決了開放問題,現在我打開第一個文件後,有一個超出範圍錯誤。最終,我試圖讀取每個文件的一個字段,並將該值檢索回我的主工作表。 – George

+0

@George哪一行會拋出錯誤? – user3561813

+0

我懷疑它是在我的循環中對於每張紙...? – George

2

有趣的問題!這應該爲你做。根據需要修改。

Sub LoopAllExcelFilesInFolder() 

'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them 
'SOURCE: www.TheSpreadsheetGuru.com 

Dim wb As Workbook 
Dim myPath As String 
Dim myFile As String 
Dim myExtension As String 
Dim FldrPicker As FileDialog 

'Optimize Macro Speed 
    Application.ScreenUpdating = False 
    Application.EnableEvents = False 
    Application.Calculation = xlCalculationManual 

'Retrieve Target Folder Path From User 
    Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker) 

    With FldrPicker 
     .Title = "Select A Target Folder" 
     .AllowMultiSelect = False 
     If .Show <> -1 Then GoTo NextCode 
     myPath = .SelectedItems(1) & "\" 
    End With 

'In Case of Cancel 
NextCode: 
    myPath = myPath 
    If myPath = "" Then GoTo ResetSettings 

'Target File Extension (must include wildcard "*") 
    myExtension = "*.xlsx" 

'Target Path with Ending Extention 
    myFile = Dir(myPath & myExtension) 
    Row = 1 
'Loop through each Excel file in folder 
    Do While myFile <> "" 
    'Set variable equal to opened workbook 
     Set wb = Workbooks.Open(Filename:=myPath & myFile) 

    'Change First Worksheet's Background Fill Blue 
     ThisWorkbook.Worksheets("Sheet1").Range("A" & Row).Value = Worksheets(1).Range("A1").Value 
     Row = Row + 1 
    'Save and Close Workbook 
     wb.Close SaveChanges:=True 

    'Get next file name 
     myFile = Dir 
    Loop 

'Message Box when tasks are completed 
    MsgBox "Task Complete!" 

ResetSettings: 
    'Reset Macro Optimization Settings 
    Application.EnableEvents = True 
    Application.Calculation = xlCalculationAutomatic 
    Application.ScreenUpdating = True 

End Sub