简体   繁体   English

VBA:如果工作簿中的工作表名称等于从用户窗体中选择的组合框值,则复制该工作表并将其粘贴到另一个工作簿中

[英]VBA: If Worksheet name in Workbook equals Combo Box value selected from Userform then copy that Worksheet and paste it into another Workbook

I am working on a Userform that will copy a specific sheet from Workbook A and paste it into Workbook B (essentially archiving that data). 我正在处理一个用户窗体,该窗体将从工作簿A复制特定的工作表并将其粘贴到工作簿B中(实质上是将数据存档)。 The Userform presents the user with a combo-box dropdown to select the sheet name to be copied. 用户表单向用户显示一个组合框下拉列表,以选择要复制的工作表名称。 I receive a subscript out of range error however when using the sheets.copy command. 但是,当我使用sheets.copy命令时,收到下标超出范围的错误。 Here is my code with names modified for ease of reading: 这是我的代码,其名称经过修改以便于阅读:

    Dim ws as Worksheet
    Dim WorkbookA as Workbook
    Dim WorkbookB as Workbook
    Dim ComboBoxValue as String


    Set WorkbookA as ActiveWorkbook
    Set WorkbookB as Workbook.Open("C:File Path Here")

    With ThisWorkbook
        For Each ws In Application.ActiveWorkbook.Worksheets
            If ws.Name = UserForm1.ComboBox1.Text Then
                ComboBoxValue = ws.Name
                Worksheets(ComboBoxValue).Copy _ 
                After:=Workbooks("Workbook B.xlsm").Sheets(Sheets.Count) 
                ' Run-Time 9 Subscript Out of Range Error occurs on line above ^
                ActiveSheet.Name = UserForm1.ComboBoxSelection.Text
                WorkbookB.Save
                WorkbookB.Close
                WorkbookA.Activate
                Application.CutCopyMode = False
            End If
        Next ws
    End With

The root of your error is improper refenceing of the workbook. 错误的根源是对工作簿的不正确引用。 There are a lot of other issues, too. 还有很多其他问题。

  • Unnecassary reference to ThisWorkbook Unnecassary参考ThisWorkbook
  • Unnecassary loop through all worksheets 遍历所有工作表的不必要的循环
  • Unnecassary renaming of copied sheet 不必要地重命名复印纸
  • Unnecassry / incorrect references to the ActiveWorkbook and ActiveSheet 没必要/对ActiveWorkbookActiveSheet引用不正确
  • No Error Handling 无错误处理
  • Improper indenting 缩进不当

Your code, refactored. 您的代码已重构。 This is written as a button click event in the UserForm. 这被写为用户窗体中的按钮单击事件。 Update to suit your needs. 更新以适应您的需求。

Option Explicit

Const ArchiveFilePath As String = "C:\Path\To\ArchiveBook.xlsx"

Private Sub CommandButton1_Click()
    Dim ws As Worksheet
    Dim WorkbookA As Workbook
    Dim WorkbookB As Workbook
    Dim wsName As String

    Application.ScreenUpdating = False

    Set WorkbookA = ActiveWorkbook

    wsName = UserForm1.ComboBox1.Text
    If wsName = vbNullString Then Exit Sub

    On Error Resume Next 'Handle possibility that Open fails
    Set WorkbookB = Workbooks.Open(ArchiveFilePath)
    On Error GoTo 0
    If WorkbookB Is Nothing Then
        MsgBox "Failed to open " & ArchiveFilePath, vbOKOnly, "Error"
        Exit Sub
    End If

    'Check if specified ws already exists in WorkbookB
    Set ws = GetWorksheet(WorkbookB, wsName)
    If Not ws Is Nothing Then
        ' Sheet already exists.  What now?
        MsgBox "Sheet " & wsName & " already exists in " & WorkbookB.Name & ".  What now?", vbOKOnly, "Error"
        WorkbookB.Close
        Exit Sub
    End If

    Set ws = GetWorksheet(WorkbookA, wsName)
    If ws Is Nothing Then
        MsgBox "Sheet " & wsName & " does not exist in " & WorkbookA.Name, vbOKOnly, "Error"
        WorkbookB.Close
        Exit Sub
    End If

    ws.Copy After:=WorkbookB.Sheets(WorkbookB.Sheets.Count)

    WorkbookB.Save
    WorkbookB.Close

    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

Private Function GetWorksheet(wb As Workbook, wsName As String) As Worksheet
    On Error GoTo EH
    Set GetWorksheet = wb.Worksheets(wsName)
EH:
End Function

Change Sheets(Sheets.Count) to Sheets(Workbooks("Workbook B.xlsm").Sheets.Count) 变更Sheets(Sheets.Count)Sheets(Workbooks("Workbook B.xlsm").Sheets.Count)

In this context, Sheets(Sheets.Count) is referring to your source workbook object, so you must specify to count the sheets in the other book. 在这种情况下, Sheets(Sheets.Count)是指您的源工作簿对象,因此您必须指定要计数另一本书中的工作表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 VBA 将工作表(带变量名)从另一个工作簿复制到当前工作簿并在当前工作簿中重命名 - VBA Copy worksheet (with variable name) from another workbook to the current workbook and rename it in the current workbook VBA将数据从一个工作簿复制到另一工作簿/工作表不起作用 - VBA to Copy data from one workbook to another workbook/worksheet not working 将数据从一个工作簿的特定工作表复制到另一个具有相同工作表名称的工作表 - Copy data from specific worksheet of a workbook to another with the same worksheet name 将多个范围从用户窗体复制到另一个工作簿中的工作表 - Copy Multiple Ranges from userform to worksheet in another workbook VBA:将文件夹中所有工作簿的范围复制到另一个工作簿中的工作表,其中包含每个 wb 的工作簿名称 - VBA: Copy a range from all workbooks in a folder to a worksheet in another workbook with workbook name from each wb included 将工作表从一个工作簿复制到另一工作簿 - Copy worksheet from one Workbook to another Workbook 用户表单以指定要复制的工作簿/工作表 - Userform to specify workbook/worksheet to copy 如何将单元格值复制并粘贴到同一工作簿中的另一个工作表 - How to copy and paste a cell value to another worksheet in the same workbook 将工作表复制/粘贴到没有该工作表的 VBA 代码的新工作簿 - Copy/Paste worksheet to new workbook without that worksheet's VBA code 将多个工作簿中的值复制并粘贴到另一个工作簿中的工作表中/在循环中粘贴值 - Copy and Paste VALUES from multiple workbooks to a worksheet in another workbook / Paste Value within Loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM