尝试复制工作表时出范围错误

时间:2016-04-14 13:24:45

标签: excel vba excel-vba macros

整个宏应该从站点打开一个文件,然后复制一个特定的工作表并粘贴到另一个工作簿中。到目前为止,宏打开但无法复制并粘贴抛出“超出范围错误”错误。我正在寻找修复该错误或打开工作簿然后删除我不想看到的额外工作表。任何帮助将不胜感激!

Public Sub OpenFileFromWeb()
' Define Workbook and Worksheet Variables
Dim wkbMyWorkbook As Workbook
Dim wkbWebWorkbook As Workbook
Dim wksWebWorkSheet As Worksheet
Set wkbMyWorkbook = ActiveWorkbook

' Open The Web Workbook
    Workbooks.Open ("http://path.path.com/path/site/path/test_Data.xls")
    Sheets("Sheet3").Select

' Set the Web Workbook and Worksheet Variables
Set wkbWebWorkbook = ActiveWorkbook
Set wksWebWorkSheet = ActiveSheet

' Choose Sheet to pull Data from
    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy

' Copy The Web Worksheet To My Workbook and Rename
    wksWebWorkSheet.Copy After:=wkbMyWorkbook.Sheets(Sheets.Count)'-->error occurs here
    wkbMyWorkbook.Sheets(ActiveSheet.Name).Name = "MyNewWebSheet"

' Close the Web Workbook
    wkbMyWorkbook.Activate
    wkbWebWorkbook.Close

End Sub

2 个答案:

答案 0 :(得分:1)

试一试

Public Sub OpenFileFromWeb()

    Dim wkbMyWorkbook As Workbook
    Dim wkbWebWorkbook As Workbook
    Set wkbMyWorkbook = ThisWorkbook

    Set wkbWebWorkbook = Workbooks.Open("http://path.path.com/path/site/path/test_Data.xls")

    With wkbMyWorkbook
        wkbWebWorkbook.Sheets("Sheet3").Copy _
            After:=.Sheets(.Sheets.Count)
        .Sheets(.Sheets.Count).Name = "MyNewWebSheet"
    End With

    ' Close the Web Workbook
    wkbMyWorkbook.Activate
    wkbWebWorkbook.Close

End Sub

答案 1 :(得分:0)

您只需要确定您在sheets.count上使用的工作簿。

我在这里整理了你的代码:

Public Sub OpenFileFromWeb()

    ' Define Workbook and Worksheet Variables
    Dim wkbMyWorkbook As Workbook
    Dim wkbWebWorkbook As Workbook
    Dim wksWebWorkSheet As Worksheet
    Set wkbMyWorkbook = ActiveWorkbook

    ' Open The Web Workbook and Set the Web Workbook and Worksheet Variables
    Set wkbWebWorkbook = Workbooks.Open("http://path.path.com/path/site/path/test_Data.xls")
    Set wksWebWorkSheet = wkbWebWorkbook.Sheets("Sheet3")

    ' Choose Sheet to pull Data from
    wksWebWorkSheet.Range("A1", Range("A1").End(xlToRight).End(xlDown)).Copy '''NOT SURE WHAT THIS IS FOR. DOESN'T SEEM TO BE REQUIRED!

    ' Copy The Web Worksheet To My Workbook and Rename
    wksWebWorkSheet.Copy after:=wkbMyWorkbook.Sheets(wkbMyWorkbook.Sheets.Count)
    wkbMyWorkbook.Sheets(ActiveSheet.Name).Name = "MyNewWebSheet"

    ' Close the Web Workbook
    wkbMyWorkbook.Activate
    wkbWebWorkbook.Close

End Sub