简体   繁体   中英

Copying from one cell to another cell on a different sheet?

I'm new to Visual Basic on Excel and I've been struggling trying to copy one cell to another on a different sheet. For example, if Sheet1 has the following:

Animal    Owner
Dog       John
Cat       Gabe

And Sheet2 is simply blank, assuming Animal and Owner are in different columns and are in columns A and B respectively, I just wanted to copy Dog into A2 (Animal is in cell A1) onto sheet two, for example.

I tried to look things up online and tried:

Dim dataSheet As Worksheet
Set dataSheet = ThisWorkbook.Sheets("Sheet1")
Dim DestinationSheet As Worksheet
Set DestinationSheet = ThisWorkbook.Sheets("Sheet2")

dataSheet.Range("A2").Copy DestinationSheet.Range("A2")

But I keep getting an error saying that:

Run-time error '1004': Method 'Range' of object '_Worksheet' failed.

I just want to copy from one cell to another onto a different worksheet. If anyone has any idea to do so, that would be great! Thanks!

dim x as integer
x = 1
do until Sheets("Sheet1").Range("A" & x).Value = ""
Sheets("Sheet2").Range("A" & x).Value = Sheets("Sheet1").Range("A" & x).Value
x = x + 1
Loop

I dont know how well this works for moving formulas and formatting around, but it works fine for values.

Here an example that gets rid of the need for a loop, this will needs to more reliable and faster execution:

Sub Sample()

Dim lngSh1LastARow As Long

'Get last row in Sheet1 Column A
lngSh1LastARow = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

'Select the same range but on sheet 2
With Sheets("Sheet5").Range("A1:A" & lngSh1LastARow)

    'Set sheet2's A column = to Sheet 1 A column
    .FormulaR1C1 = "=Sheet1!RC"

    'Remove all formulas from Sheet2 column A and retain just the value
    'Note: This step is optional If sheet1 Column A has formulas and you would
    'like to retain those formulas on sheet2 as well simply delete or 
    'Comment out the next line
    .Value = .Value

End With

End Sub

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