Workbook.Close()导致“运行时错误9”

时间:2015-09-17 09:30:12

标签: excel vba excel-vba

我对VBA有些新意,我正在尝试创建一个Sub()来从不同的Excel工作簿中读取数据。它的工作原理是打开工作簿,从中读取,然后我想再次关闭工作簿。最后一部分是导致以下错误的原因:

  

运行时错误'9':

     

下标超出范围

在尝试关闭文件时,我无法理解为什么会出现此错误。我希望你们能帮忙。如果我注释掉Close()部分......

,它就有效

代码

Option Explicit

Sub Test()
    Dim Path, Filename
    Dim sh1 As Worksheet, sh2 As Worksheet, sh3 As Worksheet, transmitWorkbook As Workbook, revieveWorkbook As Workbook

    'Define a variable for the workbook which is to recieve data
    Set revieveWorkbook = ActiveWorkbook

    Path = "C:\Test Folder\"
    Filename = "FileToReadFrom.xlsx"

    'Open workbook which is to transmit, if its not already open
    If Is_WorkBook_Open(Path & Filename) Then
        Set transmitWorkbook = Workbooks(Path & Filename)
    Else
        Set transmitWorkbook = Workbooks.Open(Path & Filename)
    End If

    revieveWorkbook.Sheets(1).Range("A1").Value = transmitWorkbook.Sheets(2).Range("F9").Value
    revieveWorkbook.Sheets(1).Range("B1").Value = Month(transmitWorkbook.Sheets(2).Range("H9").Value)

    Workbooks(Path & Filename).Close SaveChanges:=False


End Sub

1 个答案:

答案 0 :(得分:1)

正如Jeeped的评论中所提到的,路径名称不再用于关闭工作簿。正确的代码是

Workbooks(Filename).Close SaveChanges:=False

感谢大家的帮助。