我正在尝试获得一个在Excel 2011 for Mac中完美运行的宏,以便在Excel 2016 for Mac中工作。目标是让用户指定一个包含.csv文件的文件夹,然后宏循环遍历所有.csvs,打开每个文件以将信息复制到另一个工作簿中。
尝试在用户选择的文件夹中打开第一个.csv文件时,宏失败,出现1004错误,无法找到文件。
(旁注:在宏的早期,workbooks.open与用户选择的FILE完美配合)
宏是巨大的,所以我做了一个全新的小版本只是为了解决这个问题。以下是较小的测试代码,它具有相同的失败行为:
Sub Test()
Dim folderpath As Variant
Dim filename As Variant
Dim newfilename As Variant
Dim wb As Workbook
Dim newfolderpath As Variant
folderpath = MacScript("choose folder as string")
newfolderpath = Replace(folderpath, ":", "\")
MsgBox (newfolderpath)
filename = MacScript("Choose file as string")
newfilename = Replace(filename, ":", "\")
MsgBox (filename)
MsgBox (newfilename)
MsgBox (Dir(filename))
MsgBox (newfolderpath & Dir(filename))
Set wb = Workbooks.Open(newfolderpath & Dir(filename))
End Sub
所有msgbox都提供了预期值。
设置wb行给出:
Run-time error '1004'
'Hard DRIVE\USERS\DAVE\DESKTOP\CSVS\1.CSV'
无法找到。
显然文件在那里,可以打开并且有效。
非常感谢任何帮助。
答案 0 :(得分:1)
嗯,我想我找到了答案,或者至少是一个适合我项目的答案。
我从宏的早期回到了workbooks.open(用户选择的FILE),发现它正在读取它为“/users/Dave/Desktop/csvs/1.csv”。因此,即使debug和msgbox返回反斜杠,它也不知何故想要正斜杠(你是部分正确的,蒂姆)。此外,它显然截断了Mac硬盘的名称,并以users目录开头。所以,我只修改了变量以匹配这种格式,瞧,它有效。对于那些感兴趣的人,这是我使用的修改后的代码:
Sub Test()
Dim folderpath As Variant
Dim newfilename As Variant
Dim wb As Workbook
Dim newfolderpath As Variant
Dim newfp As Variant
folderpath = MacScript("choose folder as string")
newfolderpath = Replace(folderpath, ":", "/")
newfp = Right(newfolderpath, Len(newfolderpath) - InStr(newfolderpath, "/") + 1)
newfilename = Dir(newfp)
Set wb = Workbooks.Open(newfp & newfilename)
Exit Sub
感谢所有帮助过的人。