运行时错误' 9'使用简单的VBA副本表代码

时间:2018-06-01 20:11:32

标签: excel vba excel-vba

出于某种原因,我一直在收到运行时错误9:使用简单的复制表代码超出范围的下标,我似乎无法弄清楚原因。基本上,我试图从一个名为" cash"的文件中复制Sheet1。在它上面的当前工作簿(Daily Dashboard.xlsm)与命令按钮单击宏。以下是我尝试过的两个代码:

Private Sub CommandButton1_Click()
    Dim sPath As String, sName As String
    sPath = ThisWorkbook.Path & "\"
    sName = Dir(sPath & "cash*.xls?")
    If sName <> "" Then
        Windows(sName).Activate
        Sheets("Sheet1").Select
        Sheets("Sheet1").Copy After:=Workbooks("Daily Dashboard.xlsm").Sheets(Sheets.Count)
        ActiveSheet.Name = "Cash & CC Sales"
    End If
End Sub

我想我可能需要实际打开工作簿,所以我也试过下面的代码:

Private Sub CommandButton1_Click()
    Dim sPath As String, sName As String
    sPath = ThisWorkbook.Path & "\"
    sName = Dir(sPath & "cash*.xls?")
    If sName <> "" Then
        Workbooks.Open (sName)
        Sheets("Sheet1").Copy After:=Workbooks("Daily Dashboard.xlsm").Sheets(Sheets.Count)
        ActiveSheet.Name = "Cash & CC Sales"
        Workbooks(sName).Close savechanges:=False
    End If
End Sub

在第二个代码中,文件打开,但由于运行时错误,复制部分似乎无法正常工作。我在这里做错了什么想法?

1 个答案:

答案 0 :(得分:2)

您的表格参考文献并不完全正确。试试这个:

Private Sub CommandButton1_Click()
    Dim sPath As String, sName As String

    sPath = ThisWorkbook.Path & "\"
    sName = Dir(sPath & "cash*.xls?")

    If sName <> "" Then
        With Workbooks.Open(sName)
            .Worksheets("Sheet1").Copy After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
            .Close SaveChanges:=False
            ActiveSheet.Name = "Cash & CC Sales"
        End With
    End If
End Sub