如果从 Excel 中打开文件,代码仅在 Excel 2007 上运行

Code only runs on Excel 2007 if file is opened from within Excel

我有一些相对简单的代码,循环遍历文件夹中的多个文件,打开每个文件并将一系列数据复制到新工作表中。我使用 Excel 2013 编写代码。有些用户的盒子上有 2007。如果 2007 用户从 Excel 中打开文件(即文件打开,然后导航到目录),它 运行 没问题。如果 2007 用户从 Windows Explorer 打开文件,所有宏 运行,除了我在循环中使用的文件名变量 "myFile" 总是 EMPTY。就像它不会导航到目录一样。我没有收到任何错误,它只是执行代码并一直到循环的末尾(表示在 "myFile" 为空时停止)——然后继续执行下一个宏。对于 Excel 2013,程序 运行 无论以何种方式打开都没有问题。我认为我的答案可能已包含在此线程中:Excel Workbook Open Event macro doesn't always run 但问答似乎并不直接适用于我的问题,因为宏实际上 运行。似乎只是无法导航到文件位置。这是 运行 循环的代码片段:

    Dim myfile As String
Dim wb As Workbook
Dim ws As Worksheet
Dim DataBlock As Range

'Optimize Macro Speed
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

Set wb = Workbooks("ComboFile.xlsm")
Set ws = wb.Sheets("Sheet1")    'change desired sheet

ChDir "r:\BSI\Sys9000"
myfile = Dir("*.xlsx")

Do Until myfile = ""
    Workbooks.Open Filename:=myfile
    Set DataBlock = Range("A2").CurrentRegion
    DataBlock.Copy ws.Cells(ws.Rows.Count, "A").End(xlUp).Offset(1)
    Windows(myfile).Close
    myfile = Dir
Loop

'Reset Macro Optimization Settings
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

欢迎提出任何建议。谢谢你。

我建议你更换这个:

ChDir "r:\BSI\Sys9000"
myfile = Dir("*.xlsx")

只有这个:

myfile = Dir("r:\BSI\Sys9000\*.xlsx")

ChDir 不会更改驱动器,因此如果当前目录不在 R 驱动器上,代码将失败。

您还需要更改此设置:

Workbooks.Open Filename:=myfile

要包含路径:

Workbooks.Open Filename:="r:\BSI\Sys9000\" & myfile