尽管文件存在但未找到 Excel VBA 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22728599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA File not Found although file exists
提问by user3475262
I have written below piece of code to access a file and copy content from one file to the other. I am using excel 2007.
我写了下面的一段代码来访问一个文件并将内容从一个文件复制到另一个文件。我正在使用 excel 2007。
Sub copypaste()
Dim strFolder As String
Dim strFileName As String
Dim wb As Workbook
strFolder = "C:\Users\user\Desktop\sample\"
strFileName = Dir(strFolder & "*.xlsx")
Dim eRow
Dim a As Variant
Dim b As Variant
Do While Len(strFileName) > 0
**Set wb = Workbooks.Open(strFileName)**
a = Cells(7, 7)
b = Range("D11:F11")
ActiveWorkbook.Close
Worksheets("sheet1").Cells(7, 7) = a
Worksheets("sheet1").Cells(7, 8) = b
strFileName = Dir
Loop
End Sub
Although the file exists in the folder I get the error while opening the file. While in debug mode the variable strFileName contains the file name but still the file is not opening. I am getting the error at line "Set wb = Workbooks.Open(strFileName)"
虽然该文件存在于文件夹中,但我在打开文件时收到错误消息。在调试模式下,变量 strFileName 包含文件名,但文件仍未打开。我在行收到错误"Set wb = Workbooks.Open(strFileName)"
Thanks in advance for your help!!
在此先感谢您的帮助!!
回答by
Workbooks.Open requires the full path to the workbook. I suspect you want:
Workbooks.Open 需要工作簿的完整路径。我怀疑你想要:
Set wb = Workbooks.Open(strFolder & strFileName)
回答by NGI
As (gone) user user496736 stated you need to have a full path
正如(消失的)用户 user496736 所说,你需要有一个完整的路径
But most of the time your path will be very long and cumbersome to type or you will not know it in advance, so the help of ActiveWorkbook.Path
但是大多数时候你的路径会很长而且输入起来很麻烦或者你不会提前知道,所以ActiveWorkbook.Path的帮助
Exemple with readonly just for information
只读示例,仅供参考
Dim Alloc_WB As Workbook
Dim FileStr As String
FileStr = ActiveWorkbook.Path & "\" & "my_file.xlsx"
'workbook should be closed at start of code. Otherwise you get an error msg asking to re-open the Workbook
Set Alloc_WB = Workbooks.Open(Filename:=FileStr, ReadOnly:=True)
'...
'Other actions here...
'...
With Alloc_WB
.Close
End With
回答by Anthony Raymond
You need to replace all \ by double \\ in your path
您需要将路径中的所有 \ 替换为双 \\
Or add @ in front of you string.
或者在字符串前面添加@。
It is cause \ is the character for escape strings, like \n \s and so on so letter after a \ is transformed. Try to print your path, you'll see what append.
这是因为 \ 是转义字符串的字符,例如 \n \s 等等,所以 \ 转换后的字母。尝试打印您的路径,您会看到附加的内容。
EDIT
编辑
May also try :
也可以尝试:
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),");
Set wb2 = Workbooks.Open(Filename:=FileToOpen)