How to Copy and Paste in Excel VBA?
In Excel VBA, you can use the Copy
and Paste
methods to copy and paste data between cells, ranges, and worksheets. Here is an example of how to use these methods:
Example 1: Copying and Pasting Values
Sub CopyPasteValues()
Dim srcRange As Range
Dim destRange As Range
' Set the source range to be copied
Set srcRange = Range("A1:A10")
' Set the destination range for pasting
Set destRange = Range("B1:B10")
' Copy the values from source range to destination range
srcRange.Copy
destRange.PasteSpecial xlPasteValues
' Clear clipboard
Application.CutCopyMode = False
End Sub
In this example, we define two ranges: srcRange
as the source range to be copied from (A1:A10), and destRange
as the destination range where the values should be pasted (B1:B10). The Copy
method is used to copy the values from the source range, and the PasteSpecial
method with xlPasteValues
parameter is used to paste the values to the destination range. Finally, we clear the clipboard using Application.CutCopyMode = False
.
Example 2: Copying and Pasting Formats
Sub CopyPasteFormats()
Dim srcRange As Range
Dim destRange As Range
' Set the source range to be copied
Set srcRange = Range("A1:A10")
' Set the destination range for pasting
Set destRange = Range("B1:B10")
' Copy the formats from source range to destination range
srcRange.Copy
destRange.PasteSpecial xlPasteFormats
' Clear clipboard
Application.CutCopyMode = False
End Sub
This example is similar to Example 1, but instead of copying and pasting values, we only copy the formats from the source range and paste them to the destination range using the xlPasteFormats
parameter.
These are just a few basic examples of how to copy and paste in Excel VBA. Depending on your requirements, you can customize the code to suit your needs by adjusting the source and destination ranges, and using different PasteSpecial
parameters for various paste options.