Excel VBA-运行时错误1004打开工作簿

时间:2017-08-16 19:53:08

标签: excel vba excel-vba runtime-error filenames

对vba来说很新,但我编写了一个代码,用于在列中取消合并行,然后复制,然后将单元格粘贴到不同的宏工作簿中。我第一次运行时代码运行良好。然而,我今天试图使用它,我感到震惊,我有一个错误。此错误表明它找不到目标文件名。这很奇怪,因为目标文件名没有改变或移动。这是代码示例。

错误显示在第:

  

设置book2 = Workbooks.Open("财政' 17报告的跨式燃料   Usage.xlsm&#34)

代码如下:

Public Sub Button6_Click()
       'Change name of button

       Worksheets("7500").Buttons("Button 6").Text = "Send"
       With Sheets("7500")

       'Unmerge cells
       .Range("AI3:AI92").Select
       With Selection
        For Each rCell In Selection
         With rCell
         If .MergeCells Then
          .MergeArea.UnMerge
         End If
        End With
       Next rCell
       End With
      End With

      'open destination workbook

       Dim book1 As Workbook
       Dim sheet1 As Worksheet
       Dim book2 As Workbook
       Dim sheet2 As Worksheet
       Application.ScreenUpdating = False
       Set book1 = ThisWorkbook
       Set book2 = Workbooks.Open("Fiscal '17 Reported Straddle Fuel Usage.xlsm")
       Set sheet1 = book1.Sheets("7500")
       Set sheet2 = book2.Sheets("Nov ‘17")

1 个答案:

答案 0 :(得分:2)

  

目标文件名未更改或移动

您没有指定路径。指定路径。

Set book2 = Workbooks.Open("Fiscal '17 Reported Straddle Fuel Usage.xlsm")
Const path As String = "C:\Foo\Bar\Fiscal '17 Reported Straddle Fuel Usage.xlsm"
Set book2 = Workbooks.Open(path)
无论Workbooks.Open路径是什么,

CurDir都会工作,只要向用户显示"打开文件,就会更改CurDir的值。对话框,他们开始浏览:没有完整路径的文件名是不可靠的。

与VBA中的许多内容一样,最好明确一点。给它一个完整的路径。