编辑:在user3561813
添加建议之后"/"
,它现在读取第一个文件。我有一个超出范围的错误消息"9"
。它确实正确读取了第一个文件。最终,我试图打开每个文件,并读取名称和年龄(这是测试,而不是实际的生产形式)。并将值取回我的主工作表。
原始问题
我试图读取一个文件夹中的数百个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
在您的代码中,path
变量可能不包含尾部反斜杠。这会导致LoopFiles(<>)
SubRoutine中的以下代码不正确:
directory = path
fileName = Dir(directory & "*.xl??")
文件名看起来像: c:\users\name\documentshello.xlsx
尝试将上面的代码更改为:
directory = path & "\"
fileName = Dir(directory & "*.xl??")
这样可以解决问题吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句