【发布时间】:2017-02-28 03:54:46
【问题描述】:
我正在尝试从具有相同前缀的目录中的所有 Excel 文件中导入数据。数据将从这些文件中聚合并写入主文件。我已经成功地制作了一个 do while 脚本,它可以使用带有通配符的 DIR 来识别三个测试文件。但是,当我添加打开文件的命令(并立即关闭它)时,do while 在打开和关闭文件后的第一次通过后失败。注释掉 open 和 close 命令以及 do while 循环,循环 3 次以识别测试文件。最终,我想用调用 sub 来替换 open / close 命令,该 sub 将打开文件,聚合数据并将其写入主文件。我提到这一点,以防它改变编码方式。我搜索了论坛并找到了其他几种方法来实现我的一些目标,但不是全部。一个例子是文件名中的通配符。任何帮助表示赞赏。
Sub LoopThroughFiles()
Dim strName As String
Dim strPath As String
Dim strFile As String
strPath = ThisWorkbook.Path
strName = "Employee Gross Sales"
strFile = Dir(strPath & "\" & strName & "*")
Do While Len(strFile) > 0
Debug.Print strFile
' Call OpenFile(strPath, strFile) <-- Eventually will replace open / close commands below
Workbooks.Open FileName:=strPath & "\" & Dir(strPath & "\" & strFile)
' Read / Aggregate / Write data code here or in called sub
Workbooks(strFile).Close SaveChanges:=False
strFile = Dir
Loop
End Sub
Sub OpenFile(strPath, strFile)
Dim wbTarget, wbSource As Workbook
Set wbSource = Workbooks.Open(FileName:=strPath & "\" & Dir(strPath & "\" & strFile))
wbSource.Close SaveChanges:=False
End Sub
【问题讨论】:
-
您是否尝试过单步执行代码以检查错误时的值?
-
我确实尝试过单步执行代码。当我注释掉 Open 和 Close 命令时,strFile = Dir 就在 Loop 将填充下一个文件名之前。取消注释这些行和 strFile = Dir 会变成 "" 但我不知道为什么。 YowE3K 让我理顺了。