Excel 在不同工作表的多个单元格中粘贴相同的值
我必须使用VBA在excel中将一些数据从一个工作表复制粘贴到另一个工作表。 我能够将第一组数据从工作表A复制粘贴到工作表B,没有问题。 现在,我需要将表A中的相同单元格值复制到表B中的某个范围 我试图定义工作表B中的最后一个单元格和工作表B中的第一个单元格,以便定义工作表A中的值应复制的范围 这是lastrow的代码(工作正常)Excel 在不同工作表的多个单元格中粘贴相同的值,excel,vba,Excel,Vba,我必须使用VBA在excel中将一些数据从一个工作表复制粘贴到另一个工作表。 我能够将第一组数据从工作表A复制粘贴到工作表B,没有问题。 现在,我需要将表A中的相同单元格值复制到表B中的某个范围 我试图定义工作表B中的最后一个单元格和工作表B中的第一个单元格,以便定义工作表A中的值应复制的范围 这是lastrow的代码(工作正常) Last_Row2=工作表(“记录”).范围(“a1”).结束(xlDown).行 启动单元代码 legrng=Sheets(“Records”)。单元格(Rows.
Last_Row2=工作表(“记录”).范围(“a1”).结束(xlDown).行
启动单元代码
legrng=Sheets(“Records”)。单元格(Rows.count,4)。结束(xlUp)。偏移量(1)
用于将值粘贴到范围中的代码
范围(“LegRng&Last_row2”)。复制Destination=“表A中的单元格值”
我在这里收到一个错误:
范围(“LegRng&Last_row2”)。复制Destination=“表A中的单元格值”
错误是:方法“对象范围\全局”失败
你能告诉我我做错了什么吗
谢谢您的帮助/解释您有几个错误 首先,尝试引用名为LegRng&Last_row2的范围。您的工作表中不存在此范围,它不能存在,因为此名称非法 如果要设置对包含多个单元格的区域的引用,请按以下方式执行:
Sheets("Records").Range(startCell, endCell)
因此,首先需要设置对startCell
和endCell
的引用(我假设您希望最后一个单元格也位于第4列):
您可以使用其属性value
rng.Value = "value"
因此,最后您的代码应该如下所示:
With Sheets("Records")
Last_Row2 = .Range("a1").End(xlDown).Row
Set startCell = .Cells(Rows.count, 4).End(xlUp).Offset(1)
Set endCell = .Cells(Last_Row2, 4)
.Range(startCell, endCell).value = "cell value in sheet A"
End With
如果未包装在测试
startCell.Row
是否小于最后一行2
的If语句中,则接受的答案将在重新运行时引起问题,每次重新运行宏时,代码都会将表A
中的值放置在下一个单元格中
您应该始终定义和分配变量
使用Resize
可以不需要endCell
从起始单元格中删除偏移量
,可确保调整大小
Sub FillInBlankCellsWithValue()
Dim Last_Row2 As Long, startCell As Range
With Sheets("Records")
Last_Row2 = .Range("a1").End(xlDown).Row
Set startCell = .Cells(Rows.Count, 4).End(xlUp)
'Use the If statement to test that the startCell.Row is less then the Last_Row2
If startCell.Row < Last_Row2 Then
'Offset to the first empty cell and resize by subtracting the startCell.Row
'from Last_Row2, to set the range for the value from SheetA.
startCell.Offset(1).Resize(Last_Row2 - startCell.Row).Value = Sheets("SheetA").Range("A1")
'Change the worksheet and paste value's cell range, as needed
End If
End With
End Sub
子填充LankCellswithValue()
变暗最后一行2的长度,起始单元格的范围
附页(“记录”)
最后一行2=.Range(“a1”).End(xlDown).Row
设置startCell=.Cells(Rows.Count,4).End(xlUp)
'使用If语句测试startCell.Row是否小于最后一行2
如果startCell.Row
你真是太棒了:代码按照我的想法工作,回复速度快,解释力强。非常感谢。你太棒了。
Sub FillInBlankCellsWithValue()
Dim Last_Row2 As Long, startCell As Range
With Sheets("Records")
Last_Row2 = .Range("a1").End(xlDown).Row
Set startCell = .Cells(Rows.Count, 4).End(xlUp)
'Use the If statement to test that the startCell.Row is less then the Last_Row2
If startCell.Row < Last_Row2 Then
'Offset to the first empty cell and resize by subtracting the startCell.Row
'from Last_Row2, to set the range for the value from SheetA.
startCell.Offset(1).Resize(Last_Row2 - startCell.Row).Value = Sheets("SheetA").Range("A1")
'Change the worksheet and paste value's cell range, as needed
End If
End With
End Sub