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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43266597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:25:22  来源:igfitidea点击:

Copying a worksheet to another workbook using VBA

excelvbaexcel-vba

提问by Part_Time_Nerd

I am trying to copy a worksheet from the workbook that the VBA is in (ThisWorkbook) and past it into another workbook that the user has open (ActiveWorkbook). I have written a function but I cannot get it to work. I have done something similar before and I have searched the internet but I cannot find a solution or why it is failing me. What am I doing wrong?

我正在尝试从 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

回答by AlwaysData

Try this and see if it works. It will copy Sheet2 in ThisWorkbookand paste it after Sheet1 in the ActiveWorkbook

试试这个,看看它是否有效。它将复制 Sheet2ThisWorkbook并将其粘贴到 Sheet1 之后ActiveWorkbook

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

回答by user3598756

you don't need all that variable dimming and assigning:

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

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