简体   繁体   English

Excel VBA:通过命令按钮为所有工作表复制和粘贴数据

[英]Excel VBA: Copying and Pasting Data via CommandButton for all worksheets

I'm new to VBA and need some help with implementing a tool: 我是VBA的新手,在实现工具方面需要一些帮助:

Essentially, I want to create a CommandButton that automatically copies range D9:L18 and pastes it to Q9:Y18 for my active worksheet. 本质上,我想创建一个CommandButton来自动复制范围D9:L18并将其粘贴到我的活动工作表的Q9:Y18上。 Furthermore, once I press the button, I want this process to be repeated for all other worksheets (around 40) with the exception of two specific ones. 此外,一旦按下按钮,除了两个特定的工作表,我希望对所有其他工作表(大约40个)重复执行此过程。

Can you please give me a hand with this? 你能帮我个忙吗?

Your help is much appreciated - many thanks indeed. 非常感谢您的帮助-的确感谢。

Edit: 编辑:

There is an error @ Sheet.Range("D12:L18").Select for some reason - perhaps you can help me? @ Sheet.Range("D12:L18").Select发生错误Sheet.Range("D12:L18").Select出于某种原因Sheet.Range("D12:L18").Select -也许您可以帮我吗? Thanks. 谢谢。

Private Sub CommandButton1_Click()
    Dim Sheet As Worksheet

    For Each Sheet In ThisWorkbook.Worksheets
        If Sheet.Name <> "Definitions" And Sheet.Name <> "fx" And Sheet.Name <> "Needs" Then

            Sheet.Range("D12:L18").Select
            Selection.Copy
            Sheet.Range("Q12:Y18").Select
                Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

        End If
    Next
End Sub

Recording a macro to copy and paste the cells you want is the best way to get the code to copy a single sheet. 记录宏以复制和粘贴所需的单元格是获取代码以复制单张纸的最佳方法。

But to do the work in all your sheets, use this: 但是要完成所有工作表中的工作,请使用以下命令:

Private Sub CommandButton1_Click() 
    Dim Sheet As Worksheet 
    For Each Sheet In ThisWorkbook.Worksheets 
        If Sheet.Name <> "Definitions" And Sheet.Name <> "fx" And Sheet.Name <> "Needs" Then 
            Sheet.Range("D12:L18").Copy 
            Sheet.Range("Q12:Y18").PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 
        End If 
    Next 
End Sub

To add the button, go to the developer tab in excel, add an ActiveX button. 要添加按钮,请转到excel中的developer标签,添加一个ActiveX按钮。 Design mode will be turned on. 设计模式将打开。 Double click that button, the code to be run when it's clicked will be shown in VBA editor. 双击该按钮,单击该代码将在VBA编辑器中显示。 Put your copy code there inside the Private Sub YourButtonName_Click() method. 将您的复制代码放在Private Sub YourButtonName_Click()方法内。

To make the button work, turn off the design mode. 要使按钮起作用,请关闭设计模式。 (That's done in the developer tab in excel window) (在excel窗口的“开发人员”标签中完成)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM