gpt4 book ai didi

excel - 如何打开用 Dir 找到的文件?

转载 作者:行者123 更新时间:2023-12-04 22:26:04 24 4
gpt4 key购买 nike

我正在尝试遍历文件夹中的所有 Excel 文件,并将信息从 sheet3 复制并转置到主文件上的 sheet1 上。
循环函数使用文件路径和 Dir 命令返回文件位置,但在指示打开文件时显示错误消息,说:>“运行时错误 1004:我们找不到 Testfile.xls。是否可能被移动、重命名或删除?”
我已经包含了如何定义文件路径以及循环函数如何调用第一个文件的代码。当我今天早上开始编写这段代码时,我能够打开文件;但是,在更新我的 Excel(MAC 2017 版)以访问 VBA 编辑器中的更多工具后,我无法再使用 workbooks.open 打开文件.
我试过Application.FileDialog(msoFileDialogFolderPicker)而不是说明文件路径,但对话框没有打开。我不确定我是否需要恢复到早期版本的 Excel,或者我的语法是否存在我忽略的问题,这可以解释为什么我的错误框可以告诉我文件名但认为不是在文件夹中。

Sub LoopThroughDirectory()

Dim MySource As String
'the name for file that data will come from
Dim Filepath As String

Filepath = "/Users/Victor/Desktop/Clocks/"
'the folder that files are located in
MySource = Dir(Filepath)
'define location of source files

'Establish loop
Do While Len(MySource) > 0
If MySource = "zzmaster.xlsx" Then
Exit Sub
End If
'process should loop through all files in the directory until it reaches the master file...
'master file should be the last file in the folder, so loop contains all relevant files

'begin loop
Set wb1 = Workbooks.Open(MySource) <--the error generates at this step
DoEvents

'Opens source file
代码从 zzmaster.xlsx 文件运行,该文件与五个测试文件一起位于我桌面上的一个文件夹中。我没有使用这种语言的经验来识别错误是在语法、我的文件管理中还是在我更新 Excel 的决定中。

最佳答案

Dir只返回文件夹中每个文件的文件名。当您尝试打开它时,VBA 正在查看当前工作目录。要在其他位置打开文件,您需要使用完整路径:

Set wb1 = Workbooks.Open(Filepath + MySource) 

关于excel - 如何打开用 Dir 找到的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57795419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com