将数据从一个工作表拉到另一个工作表

时间:2013-04-16 18:26:43

标签: excel excel-vba excel-2010 vba

我希望有人可以帮助我,因为我已尝试过其他网站的许多建议,但无法找到解决方案。

我有2本工作簿。一个包含要复制到另一个的字段列表。到目前为止看起来很容易,但是当我尝试将工作表名称分配给变量时,它不会存储它,因此我以后无法返回该工作表。

我会举个例子

Function getActiveWBName()
    getActiveWBName = ActiveWorkbook.NAME
End Function

Dim homeWB

Sub pull_data()
    Set homeWB = Workbooks(getActiveWBName)
    homeWB.Activate
    Call Update_List
End Sub

Sub Update_List()
    Workbooks.Open Filename:=FullFilePath, UpdateLinks:=3

    Sheets("List").Activate
    Cells.Select
    Selection.Copy
    ActiveWorkbook.Close

    homeWB.Activate
    Sheets("List").Activate
    Range("A1").Select
    Selection.Paste
End Sub

homeWB.activate中转到sub Update_List后,它会返回runtime error 424 - Object required.

我做错了什么?

我想保留返回活动工作表名称的函数。

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

你不必走那条路:)我不确定你提到的网站,但你应该避免使用.Select.Activate。见this

您的代码可以重写为(更改适用时)

Sub Sample()
    Dim wbInput As Workbook, wbOutput As Workbook
    Dim wsInput As Worksheet, wsOutput As Worksheet

    '~~> From where you want to copy
    Set wbInput = ThisWorkbook
    '~~> This is the sheet which has the fields you want to copy
    Set wsInput = wbInput.Sheets("List")

    '~~> Destination workbook
    Set wbOutput = Workbooks.Open("C:\Sample.xlsx")
    '~~> Destination sheet
    Set wsOutput = wbOutput.Sheets("List")

    '~~> Copy the relevant range
    wsInput.Range("A1:A10").Copy wsOutput.Range("A1")
End Sub

答案 1 :(得分:0)

您收到了Object Required错误,因为homeWB未声明为公共变量,也未传递给Update_List子例程。

您可以通过将变量homeWB传递给Update_List子例程来解决此问题:

Sub pull_data()
Set homeWB = Workbooks(getActiveWBName)
homeWB.Activate
Call Update_List(homeWB)

End Sub

Sub Update_List(homeWB as Workbook)
Workbooks.Open Filename:=FullFilePath, UpdateLinks:=3

Sheets("List").Activate
Cells.Select
Selection.Copy
ActiveWorkbook.Close

homeWB.Activate
Sheets("List").Activate
Range("A1").Select
Selection.Paste
End Sub

但是,我会注意上面的Siddhart Rout关于使用ActivateSelect的建议,这应该在99%的时间内避免使用。

答案 2 :(得分:0)

尝试以下代码。

Dim homeWB As Workbook
Const FullFilePath = "C:\Users\Santosh\Desktop\ssss.xlsx" ' specify your path here

Sub pull_data()
    Set homeWB = ThisWorkbook
    Call Update_List
End Sub

Sub Update_List()

    Dim wkb As Workbook
    Set wkb = Workbooks.Open(Filename:=FullFilePath, UpdateLinks:=xlUpdateLinksAlways)
    wkb.Sheets("List").Cells.Copy homeWB.Sheets("List").Range("A1")

    wkb.Close
End Sub