简体   繁体   English

Excel VBA中的“下标超出范围”

[英]“subscript out of range” in excel vba

I am getting "subscript out of range" in excel vba at the line "Workbooks("source").Sheets("Sheet1").Activate" 我在excel vba中的"Workbooks("source").Sheets("Sheet1").Activate"行中收到“下标超出范围"Workbooks("source").Sheets("Sheet1").Activate"

Sub one()
    Dim target As Object
    Set target = ThisWorkbook

    source = Application.GetOpenFilename( _
        FileFilter:="Excel 2003 (*.xls),*.xls,Excel 2007 (*.xlsx),*.xlsx,Excel 2007 (*.xlsm),*.xlsm", _
        Title:="Select an the sdlc workbook", _
        MultiSelect:=File)
    If source = False Then
        Exit Sub
    Else
        Workbooks.Open Filename:=source
    End If
    Workbooks("source").Sheets("Sheet1").Activate
End Sub

It appears source is a variable, not the actual name of the workbook. 看来source是一个变量,而不是工作簿的实际名称。 It would be easier to use a Workbook variable rather than the name: 使用Workbook变量而不是名称会更容易:

Sub one()
    Dim target As Excel.Workbook
    Set target = ThisWorkbook
    Dim wbSource as Excel.Workbook

    source = Application.GetOpenFilename( _
        FileFilter:="Excel 2003 (*.xls),*.xls,Excel 2007 (*.xlsx),*.xlsx,Excel 2007 (*.xlsm),*.xlsm", _
        Title:="Select an the sdlc workbook", _
        MultiSelect:=File)
    If source = False Then
        Exit Sub
    Else
        Set wbSource = Workbooks.Open(Filename:=source)
    End If
    wbSource.Sheets("Sheet1").Activate
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM