简体   繁体   中英

Excel VBA Copy Paste error

I have two sheets of same data

A  B  C
   5  6
4  3  3 

Formula 1

Sub Button1_Click()

Dim Current As Worksheet


  Range("A2").Copy _
  Destination:=Range("A1")
  Range("A2").ClearContents         

End Sub

The formula works for me. But I need to apply this script to all sheets,

Formula 2

Dim Current As Worksheet

         ' Loop through all of the worksheets in the active workbook.
         For Each Current In ThisWorkbook.Worksheets
    With Current



           Range("A2").Copy _ Destination:=Range("A1")
  Range("A2").ClearContents
            End With
         Next Current


End Sub

--> It works but values in A1 also deleted. And it is not being used for all sheets. Only active sheets.

A With ... End With statement can carry a parent worksheet reference along in a block of commands but you must prefix each .Range or .Cells reference with a period (aka full stop ) to accept the parent worksheet relationship.

Dim Current As Worksheet

' Loop through all of the worksheets in the active workbook.
For Each Current In ThisWorkbook.Worksheets
    With Current
       .Range("A2").Copy Destination:=.Range("A1")
       .Range("A2").ClearContents
    End With
Next Current

Note .Range and not Range .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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