[英]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. 我是Excel上Visual Basic的新手,我一直在努力将一个单元格复制到另一张工作表上的另一个单元中。 For example, if
Sheet1
has the following: 例如,如果
Sheet1
具有以下内容:
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. 并且
Sheet2
只是空白,假设Animal
和Owner
分别在不同的列中并且分别在columns A
和B
columns A
,我只想将Dog
复制到A2(动物在单元格A1中)到第二张工作表中。
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.
运行时错误'1004':对象'_Worksheet'的方法'Range'失败。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.