使用Workbook的Excel VBA。打开Dir(目录)的结果

时间:2015-02-11 18:24:01

标签: excel vba excel-vba

这看起来很简单,而且我已经多次工作了,但是我的Dir调用(迭代目录)和打开当前文件之间的某些东西一直存在。这是相关的代码:

SourceLoc = "C:\ExcelWIP\TestSource\"
SourceCurrentFile = Dir(SourceLoc)

'Start looping through directory
While (SourceCurrentFile <> "")
Application.Workbooks.Open (SourceCurrentFile)

我得到的是文件访问错误,因为Application.Workbooks.Open正在尝试打开&#34; C:\ ExcelWIP \ TestSource \\ FILENAME&#34; (注意额外的斜线)

然而,当我从SourceLoc中取出最终的斜杠时,Dir(SourceLoc)的结果是&#34;&#34; (它不会搜索目录)。

令人沮丧的是,当我以其他方式编辑子时,此代码的功能已经过去了。我已经按原样工作了,而且我已经接受了&#39; /&#39;超出目录路径使它工作,而目前,我只是不能让它们一起工作。

我已经搜索了在线帮助和ms文章,但似乎没有任何东西可以指出为什么它会继续上下(没有被编辑,除非它停止工作)以及为什么目录路径的格式将会有时与最终的&#39; /&#39;有时没有。

任何想法?

3 个答案:

答案 0 :(得分:1)

这将打开该目录中的所有.xlsx文件。

    Sub OpenFiles()
    Dim SourceCurrentFile As String
    Dim FileExtension as String: FileExtension = "*.xlxs"
    SourceLoc = "C:\ExcelWIP\TestSource\"
    SourceCurrentFile = Dir(SourceLoc)
    SourceCurrentFile = Dir()
    'Start looping through directory
    Do While (SourceCurrentFile <> "")
    Application.Workbooks.Open (SourceLoc &"\"& SourceCurrentFile)
    SourceCurrentFile = Dir(FileExtension)
    Loop
    End Sub

答案 1 :(得分:1)

JLILI Aman找到了将Dir()的结果作为字符串的答案。使用它与Application.Open上的路径结合使用可以从代码中获得稳定的行为。

新守则:

Dim SourceLoc as String
Dim SourceCurrentFile as String
SourceLoc = "C:\ExcelWIP\TestSource\"
SourceCurrentFile = Dir(SourceLoc)

'Start looping through directory
While (SourceCurrentFile <> "")
Application.Workbooks.Open (SourceLoc & "/" & SourceCurrentFile)

我没有包含推荐的文件扩展名,因为我在一个目录中处理xls,xlsx和xlsm文件。此代码打开所有这些代码。

警告 - 此代码将当前文件设置为目录中的每个文件,包括非excel文件。在我的情况下,我只处理excel文件,所以这不是问题。

至于为什么会发生这种情况,Application.Open似乎不会接受Dir()的完整对象结果,所以Dir()的返回需要是一个String。我没有深入研究它之外的原因。

答案 2 :(得分:0)

考虑使用VBA&#39; FileSystemObject,其中包含文件夹和文件属性:

Sub xlFilesOpen()
    Dim strPath As String
    Dim objFSO As Object, objFolder As Object, xlFile As Object

    strPath = "C:\ExcelWIP\TestSource"

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder(strPath)

    For Each xlFile In objFolder.Files
        If Right(xlFile, 4) = "xlsx" Or Right(xlFile, 3) = "xls" Then
            Application.Workbooks.Open (xlFile)
        End If
    Next xlFile

    Set objFSO = Nothing
    Set objFolder = Nothing
End Sub