尽管文件存在,但找不到Excel VBA文件

时间:2014-03-29 08:02:16

标签: excel-vba vba excel

我在下面写了一段代码来访问文件并将内容从一个文件复制到另一个文件。我正在使用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

虽然文件夹中存在该文件,但在打开文件时出现错误。在调试模式下,变量strFileName包含文件名,但文件仍未打开。我在第"Set wb = Workbooks.Open(strFileName)"

收到错误

先谢谢你的帮助!!

3 个答案:

答案 0 :(得分:2)

Workbooks.Open需要工作簿的完整路径。我怀疑你想要:

Set wb = Workbooks.Open(strFolder & strFileName)

答案 1 :(得分:0)

您需要在路径中替换所有\ by double \\

或者在你前面添加@字符串。

原因是\是转义字符串的字符,比如\ n \ s等等,所以转换后的字母。 尝试打印你的路径,你会看到附加的内容。

修改

也可以尝试:

FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.xls (*.xls),");
Set wb2 = Workbooks.Open(Filename:=FileToOpen)

答案 2 :(得分:0)

(过去的)用户user496736表示您需要完整的路径

但是大多数情况下,您的路径会很长且很难输入,或者您可能不会事先知道,因此请 ActiveWorkbook.Path

仅提供只读信息的示例

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