繁体   English   中英

VBA 运行时错误打开文件夹中的文件

[英]VBA Run-time Error Opening Files in a Folder

我正在尝试打开指定文件夹中的所有文件。 这是我拥有的代码(我已将 Path 和 FolderName 设置为通用但它们可以工作,并且当我运行它时,代码会获得正确的路径和正确的文件夹名称):

'''

Dim FolderName As String, FSOLibrary As Object, FSOFolder As Object, FSOFile As Object

FolderName = Path
'set all the references to the FSO Library
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Set FSOFolder = FSOLibrary.GetFolder(FolderName)

Set FSOFile = FSOFolder.Files

For Each FSOFile In FSOFile
currentfile = FSOFile.Name
Workbooks.Open FSOFile.currentfile

'''

当我执行代码时出现运行时错误,object 不支持此属性或方法。 但是,当前文件始终具有正确的文件路径和名称。 不确定为什么它无法打开文件。

你必须传递给Workbooks.Open一个完整的文件名,在你的情况下,我认为它是

Workbooks.Open Path & "\" & currentfile

您的代码的改进版本看起来像

Dim FolderName As String, FSOLibrary As Object, FSOFolder As Object, FSOFile As Object, FSOFiles As Object
    
FolderName = Path
'set all the references to the FSO Library
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Set FSOFolder = FSOLibrary.GetFolder(FolderName)
    
Set FSOFiles = FSOFolder.Files

For Each FSOFile In FSOFiles
    Workbooks.Open FSOFile.Path & "\" & FSOFile.Name
    'Debug.Print FSOFile.Path & "\" & FSOFile.Name
Next

我注意到两件事,我相信在 VBA 中使用 For Each 时,您需要首先创建一个 Variant 类型的变量。 此外,您已经For Each FSOFile in FSOFile这无论如何都是无效的,因为您试图通过自身循环变量......

尝试将代码的底部更改为:

Set FSOFiles = FSOFolder.Files

Dim FSOFile as Variant

For Each FSOFile in FSOFiles
currentfile = FSOFile.Name
Workbooks.Open FSOFile.currentfile

除非有特定原因要使用 FileSystemObject,否则我发现使用 Dir 更快更容易:

Sub tgr()
    
    Dim sFolderPath As String
    Dim sFileName As String
    
    sFolderPath = "C:\Temp\SO\"
    If Right(sFolderPath, 1) <> "\" Then sFolderPath = sFolderPath & "\"    'Just ensuring sFolderPath ends with a \
    
    sFileName = Dir(sFolderPath & "*.xls*") 'The "*.xls*" will ensure that only Excel files are found
    
    'Begin loop, sFileName will only be populated if a file matching the Dir filter was found
    Do While Len(sFileName) > 0
        
        'Open the file
        With Workbooks.Open(sFolderPath & sFileName)
            'Do stuff with the opened file
            MsgBox .Worksheets(1).Range("A1").Value
            
            .Close SaveChanges:=False    'Close the file when done with it, choose to save changes or not
        End With
        
        sFileName = Dir()   'Advance sFileName to the next file matching the previously set Dir filter
    Loop    'Close loop
    
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM