2016-06-08 110 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