0

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

我有 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.activatesub Update_List返回runtime error 424 - Object required.

我究竟做错了什么?

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

谁能帮我解决这个问题?

4

3 回答 3

1

你不必走那条路:)我不确定你指的是哪个网站,但你应该避免使用.Selectand .Activate。看到这个

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

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
于 2013-04-16T18:33:46.903 回答
0

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

您可以通过将变量传递homeWBUpdate_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 的上述建议,关于99%ActivateSelect时间应该避免使用。

于 2013-04-16T18:51:53.663 回答
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
于 2013-04-16T18:59:10.127 回答