使用VBA将工作表复制到另一个工作簿

时间:2017-04-06 22:11:36

标签: excel vba excel-vba

我正在尝试从VBA所在的工作簿中复制工作表(ThisWorkbook)并将其传递到用户已打开的另一个工作簿(ActiveWorkbook)。我写了一个函数,但我无法让它工作。我以前做过类似的事情,我搜索过互联网,但我找不到解决办法,或者为什么失败了。我做错了什么?

 Function workBooks() As String
    aWbkName = ActiveWorkbook.Name
    tWbkName = ThisWorkbook.Name

    Dim wbk1 As Workbook
    Dim wbk2 As Workbook

    Set wbk1 = tWbkName
    Set wbk2 = aWbkName

    wbk1.Sheet2.Copy After:=wbk2.Sheets(7)

End Function

2 个答案:

答案 0 :(得分:4)

试试这个,看它是否有效。它将在ThisWorkbook中复制Sheet2并将其粘贴到ActiveWorkbook

中的Sheet1之后
Option Explicit

Public Sub copy_sheet()

    Dim source_worksheet As Worksheet
    Set source_worksheet = ThisWorkbook.Worksheets("Sheet2")

    Dim target_worksheet As Worksheet
    Set target_worksheet = ActiveWorkbook.Worksheets("Sheet1")

    source_worksheet.Copy After:=target_worksheet

End Sub

答案 1 :(得分:1)

你不需要所有变量调光和分配:

Sub workBooks()
    ThisWorkbook.Sheet2.Copy After:=ActiveWorkbook.Sheets(7)
End Sub