Dica: outros idiomas são traduzidos pelo Google. Você pode visitar o English versão deste link.
Entrar
x
or
x
x
Registre-se
x

or

Como criar um botão de comando para copiar e colar dados no Excel?

Supondo que você precise copiar freqüentemente um intervalo de células para outro lugar depois de alterar os dados, o método de copiar e colar manual será exigente e demorado. Como fazer isso copiar e colar affair executando automaticamente? Este artigo irá mostrar-lhe como usar um botão de comando para copiar e colar dados com apenas um clique.

Crie um botão de comando para copiar e colar dados com o código VBA

Guia do Office Habilitar Edição e Navegação por Guias no Office e Facilitar seu Trabalho ...
Kutools for Excel - A melhor ferramenta de produtividade do Office resolverá a maioria dos problemas do Excel
  • Reutilizar qualquer coisa: Adicione as fórmulas, gráficos e outras coisas mais usadas ou complexas aos seus favoritos e reutilize-os rapidamente no futuro.
  • Mais do que recursos de texto 20: Extrair Número da Cadeia de Texto; Extrair ou remover parte dos textos; Converta números e moedas em palavras inglesas ...
  • Mesclar Ferramentas: Várias pastas de trabalho e folhas em um; Mesclar várias células / linhas / colunas sem perder dados; Mesclar linhas duplicadas e soma ...
  • Ferramentas de divisão: Dados divididos em várias folhas com base no valor; Uma pasta de trabalho para vários arquivos Excel, PDF ou CSV; Uma coluna para várias colunas ...
  • Colar pulando Linhas ocultas / filtradas; Contagem e Soma pela cor de fundo; Criar lista de discussão e Envie e-mails pelo valor da célula...
  • Super Filtro: Crie esquemas de filtro avançados e aplique a qualquer folha; tipo por semana, dia, frequência e mais; filtros por negrito, fórmulas, comentário ...
  • Mais de recursos poderosos do 300; Funciona com o Office 2007-2019 e 365; Suporta todos os idiomas; Fácil implantação na empresa; Recursos completos Avaliação gratuita de um dia de 60.

Crie um botão de comando para copiar e colar dados com o código VBA


Faça o seguinte para copiar e colar dados automaticamente ao clicar em um botão de comando.

1. Insira um botão de comando clicando Developer > inserção > Botão de comando (controle ActiveX). Ver captura de tela:

2. Desenhe um botão de comando em sua planilha e clique com o botão direito. Selecione Ver código no menu de contexto.

3. Na aparência Microsoft Visual Basic para Aplicações janela, substitua o código original na janela Código com código VBA abaixo.

Código VBA: use o botão de comando para copiar e colar dados no Excel

Private Sub CommandButton1_Click()
    Application.ScreenUpdating = False
    Dim xSheet As Worksheet
    Set xSheet = ActiveSheet
        If xSheet.Name <> "Definitions" And xSheet.Name <> "fx" And xSheet.Name <> "Needs" Then
            xSheet.Range("A1:C17 ").Copy
            xSheet.Range("J1:L17").PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        End If

    Application.ScreenUpdating = True
End Sub

notas: No código, CommandButton1 é o nome do seu botão de comando inserido. A1: C17 é o intervalo que você precisa copiar, e J1: L17 é o intervalo de destino para colar dados. Por favor altere-os conforme você precisa.

4. Pressione outro + Q chaves para fechar Microsoft Visual Basic para Aplicações janela. E desligue o modo de design na guia Desenvolvedor.

5. Agora, clique no botão de comando, todos os dados no intervalo A1: C17 será copiado e colado no intervalo J1: L17 sem a formatação da célula.


Artigos relacionados:


Kutools for Excel - A Melhor Ferramenta de Produtividade no Escritório Aumenta Sua Produtividade em 80%

  • armadilha para peixes: Inserir rapidamente fórmulas complexas, gráficos e qualquer coisa que você tenha usado antes; Criptografar células com senha; Criar lista de endereços e enviar e-mails ...
  • Bar Super Fórmula (facilmente editar várias linhas de texto e fórmula); Layout de leitura (leia e edite facilmente grandes números de células); Colar para intervalo filtrado...
  • Mesclar células / linhas / colunas sem perder dados; Conteúdo de células divididas; Combinar linhas / colunas duplicadas... Prevenir Células Duplicadas; Comparar intervalos...
  • Selecione Duplicado ou Exclusivo Linhas; Selecione linhas em branco (todas as células estão vazias); Super Find e Fuzzy Find em muitos livros de trabalho; Seleção aleatória ...
  • Cópia exata Múltiplas Células sem alterar a referência da fórmula; Criar automaticamente referências para várias folhas; Inserir marcadores, Caixas de seleção e mais ...
  • Extrair texto, Adicionar texto, remover por posição, Remover espaço; Criar e imprimir subtotais de paginação; Converter entre conteúdo de células e comentários...
  • Super Filtro (salve e aplique esquemas de filtro a outras planilhas); Classificação Avançada por mês / semana / dia, frequência e mais; Filtro especial por negrito, itálico ...
  • Combinar pastas de trabalho e planilhas; Mesclar tabelas com base em colunas-chave; Dividir dados em várias planilhas; Lote Converter xls, xlsx e PDF...
  • Mais de recursos poderosos do 300. Suporta Office / Excel 2007-2019 e 365. Suporta todos os idiomas. Fácil implantação em sua empresa ou organização. Recursos completos Avaliação gratuita de um dia de 60.
kte tab 201905

A guia Office traz a interface com guias para o Office e torna seu trabalho muito mais fácil

  • Ativar edição e leitura com guias no Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Abra e crie vários documentos em novas guias da mesma janela, em vez de em novas janelas.
  • Aumenta sua produtividade em 50% e reduz centenas de cliques do mouse para você todos os dias!
fundo officetab
Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Jonas · 4 days ago
    Hello!
    Is there a way to make a code so i can have a button copy a range (lets say A1:D5).
    And then paste it to A6:D10.

    And if i press the button once more it will copy A1:D5 to A11:D15.

    And so on?
  • To post as a guest, your comment is unpublished.
    Lexi · 18 days ago
    Is it possible to make a button that just copies one selected cell on one sheet to another sheet? Thanks!
    • To post as a guest, your comment is unpublished.
      crystal · 10 days ago
      Hi lexi,
      The below VBA code can help you solve the problem. Please change "Sheet3" to the sheet name as you need.
      Select a cell and press the command button to make it work.

      Private Sub CommandButton1_Click()
      Dim xSWName As String
      Dim xSheet As Worksheet
      Dim xPSheet As Worksheet
      Dim xIntR As Integer
      xSWName = "Sheet3"
      On Error Resume Next
      Application.ScreenUpdating = False
      Set xSheet = ActiveSheet
      If xSheet.Name <> "Definitions" And xSheet.Name <> "fx" And xSheet.Name <> "Needs" Then
      Selection.CurrentRegion.Select
      Selection.Copy
      Set xPSheet = Worksheets.Item(xSWName)
      xIntR = xPSheet.UsedRange.Rows.Count
      xPSheet.Cells(xIntR + 1, 1).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
      End If
      Application.ScreenUpdating = True
      End Sub
  • To post as a guest, your comment is unpublished.
    S J · 1 months ago
    please send VBAcode for copy single cell content using commmand button click without using text box so tha will be able to paste in any application like notepad,msword
  • To post as a guest, your comment is unpublished.
    angela · 3 months ago
    master bagaimana jika berbeda sheet dan copy data yg diinginkan
    contoh sheet1 hanya data kolom B & kolom D copy ke sheet2
    terimakasih
  • To post as a guest, your comment is unpublished.
    Ted Jillett · 4 months ago
    I'm looking for some help on that a user can click on a row number and then hit the command button that it will make a copy of that row and insert it into the row below it.
    • To post as a guest, your comment is unpublished.
      crystal · 2 months ago
      Good day,
      Sorry can help you with that yet. Thanks for your comment.
  • To post as a guest, your comment is unpublished.
    Yesaya · 5 months ago
    hi, help my case, i want have a button to generate macro where i have excel and export the data where in the <" "> to word, thanks
    • To post as a guest, your comment is unpublished.
      crystal · 4 months ago
      Hi,
      Sorry I didn't get your point. Would be nice if you could explain with more details of what you are trying to do.
  • To post as a guest, your comment is unpublished.
    Kyaw Ye Min · 5 months ago
    Hi Author,

    The article you mentioned above is very helpful to me. I am not used to excel code and command. I still need to know rather than this article. I am ok with the copy and paste into next sheet. But I still need to know "how to paste and add into new line in next sheet every time I press the button". Otherwise, my data on next sheet will be replaced every time. I would really be grateful and looking forward to see your reply.
    • To post as a guest, your comment is unpublished.
      crystal · 2 months ago
      Hi Kyaw Ye Min,
      Sorry for replying so late. Follow the steps and replace the code with the below. In the code, Sheet4 is the destination worksheet you will copy data into, please change it and the copied range A1:C17 as you need. Thanks for your comment.

      Private Sub CommandButton1_Click()
      Dim xSWName As String
      Dim xSheet As Worksheet
      Dim xPSheet As Worksheet
      Dim xIntR As Integer
      xSWName = "Sheet4"
      On Error Resume Next
      Application.ScreenUpdating = False
      Set xSheet = ActiveSheet
      If xSheet.Name <> "Definitions" And xSheet.Name <> "fx" And xSheet.Name <> "Needs" Then
      xSheet.Range("A1:C17 ").Copy
      Set xPSheet = Worksheets.Item(xSWName)
      xIntR = xPSheet.UsedRange.Rows.Count
      xPSheet.Cells(xIntR + 1, 1).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
      End If
      Application.ScreenUpdating = True
      End Sub
      • To post as a guest, your comment is unpublished.
        Chris · 1 months ago
        Hi there please help. I require the same as above but i just need to paste whatever the active cell is into a new line (if possible above previous entries) in a different worksheet. Really appreciate any help with this. Best Regards
  • To post as a guest, your comment is unpublished.
    Jim · 6 months ago
    I have a qusrion I have sheet 1 with a column of date b3:b33 and I want that to be copied to sheet 2 B33:b63 its text but I need the same format for text ie colour size
  • To post as a guest, your comment is unpublished.
    Robbert · 6 months ago
    If I want to Copy this not in the current workbook but into another workbook (which is still not opened) in excel. How do I change this VBA code accordingly?
    • To post as a guest, your comment is unpublished.
      crystal · 6 months ago
      Hi Robbert,
      Sorry can't help you with that. Thanks for commenting.
  • To post as a guest, your comment is unpublished.
    MangkaNorr · 8 months ago
    sir how to copy the range of the cell in current worksheet then paste to another worksheets ?
    • To post as a guest, your comment is unpublished.
      crystal · 7 months ago
      Hi,
      The below VBA code can help you solve the problem.
      You need to replace the "Sheet4" and "A1:C17" in the code with your specified sheet and range.

      Private Sub CommandButton1_Click()
      Dim xSWName As String
      Dim xSheet As Worksheet
      Dim xPSheet As Worksheet
      Dim xIntR As Integer
      xSWName = "Sheet4"
      On Error Resume Next
      Application.ScreenUpdating = False
      Set xSheet = ActiveSheet
      If xSheet.Name <> "Definitions" And xSheet.Name <> "fx" And xSheet.Name <> "Needs" Then
      xSheet.Range("A1:C17 ").Copy
      Set xPSheet = Worksheets.Item(xSWName)
      xIntR = xPSheet.UsedRange.Rows.count
      xPSheet.Cells(xIntR + 1, 1).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
      End If
      Application.ScreenUpdating = True
      End Sub
  • To post as a guest, your comment is unpublished.
    Adam · 10 months ago
    Would it be possible to for the command button to instantly paste the selected range to a specified sheet (in the next empty cell) rather than having to input each time where you want to paste the data?
    • To post as a guest, your comment is unpublished.
      crystal · 7 months ago
      Hi Adam,
      The below VBA code can help you solve the problem.
      You need to replace the "Sheet4" and "A1:C17" in the code with your specified sheet and range.

      Private Sub CommandButton1_Click()
      Dim xSWName As String
      Dim xSheet As Worksheet
      Dim xPSheet As Worksheet
      Dim xIntR As Integer
      xSWName = "Sheet4"
      On Error Resume Next
      Application.ScreenUpdating = False
      Set xSheet = ActiveSheet
      If xSheet.Name <> "Definitions" And xSheet.Name <> "fx" And xSheet.Name <> "Needs" Then
      xSheet.Range("A1:C17 ").Copy
      Set xPSheet = Worksheets.Item(xSWName)
      xIntR = xPSheet.UsedRange.Rows.count
      xPSheet.Cells(xIntR + 1, 1).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
      End If
      Application.ScreenUpdating = True
      End Sub
      • To post as a guest, your comment is unpublished.
        Mohamed shoman · 7 months ago
        very good , i need to copy and paste many time is it possible to make a choice to paste a row of data to 3 rows or 5 rows whatever i like ?
  • To post as a guest, your comment is unpublished.
    Jeff McCollum · 10 months ago
    I would like to expand this one step... After pasting the actual values not formulas... I need to copy the new cell and paste in another program that's not excel, should simply I need to click the button copy the formula from a specific cell and past the actual value in another, then copy that new value to windows clipboard to past in another app. Hope this make sense, and appreciate your help in knowing how to add the new code... I know what I want it to do, just not familiar with how to code it...
    Thanks
    • To post as a guest, your comment is unpublished.
      crystal · 9 months ago
      Hi,
      The code has been updated in the article, please have a try. Thank you for your comment.
  • To post as a guest, your comment is unpublished.
    Magnus · 11 months ago
    What if I would like to make a paste queue?
    To explain further. I click CommandButton1 then it copy A1. When I have used paste, the copy from A1 - Then I want to copy A2 without clicking another button, so that I can paste A2 right away, somewhere else. Then When I have used paste, the copy from A2 then copy A3. If that is possible? Can this also work in the background when use a normal Excel sheet, and try to do this action where I copy from Excel, and then paste in a completely different program like a internet browser, another program, word, txt file, and so on?

    This article was anyway extremely helpful, thank you so much!
    • To post as a guest, your comment is unpublished.
      crystal · 10 months ago
      Hi Magnus,
      Sorry can't help you with that. Thanks for your comment.
  • To post as a guest, your comment is unpublished.
    Azam as · 1 years ago
    how is the formula for us to copy files
    then paste it to the next sheet. and paste the next one make a space or keep going down without deleting the previous paste.
    • To post as a guest, your comment is unpublished.
      crystal · 11 months ago
      Good day,
      The below VBA code can help you solve the problem. Please have a try. Thank you.

      Private Sub CommandButton1_Click()
      Dim xSheet, xDWS As Worksheet
      Dim xFNum As Integer
      Dim xSRg As Range

      On Error Resume Next
      Set xSRg = Application.InputBox("Please select cell to paste the range:", "Kutools for Excel", xTxt, , , , , 8)
      If xSRg Is Nothing Then Exit Sub

      Application.ScreenUpdating = False
      Range("A1:C17 ").Copy
      xSRg.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
      Application.ScreenUpdating = True

      End Sub
  • To post as a guest, your comment is unpublished.
    Jason · 1 years ago
    How can you alter the code to paste the results to another page with in the workbook? and how do you get the insert a row before putting the new data in so it does not overwrite it
    • To post as a guest, your comment is unpublished.
      crystal · 1 years ago
      Hi Jason,
      If you want to paste the results to another worksheets within the workbook, please try the below VBA code.

      Private Sub CommandButton1_Click()
      Dim xSheet, xDWS As Worksheet
      Dim xFNum As Integer
      Dim xSRg As Range

      On Error Resume Next
      Set xSRg = Application.InputBox("Please select cell to paste the range:", "Kutools for Excel", xTxt, , , , , 8)
      If xSRg Is Nothing Then Exit Sub

      Application.ScreenUpdating = False
      Range("A1:C17 ").Copy
      xSRg.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
      Application.ScreenUpdating = True

      End Sub
  • To post as a guest, your comment is unpublished.
    Dom · 2 years ago
    I have used this function in my workbook. I am using active x buttons to copy and paste data within the same sheet on multiple sheets. However there are sheets without active x buttons or macros that get pasted data from the respective fields on the sheet which I don't want. Help?