将行与范围复制到另一个工作表

我的要求是将sheet3中具有字体颜色黑色的行复制到sheet1.I在工作簿中有一个从sheet3中select的行的范围。 我想复制这个并粘贴到sheet1.Selection部分是好的,但在复制语句中的错误(应用程序定义或对象定义)。

Sub Copy() Dim lastRow, i As Long Dim CopyRange As Range lastRow = Sheet3.Rows.Count With Sheets(Sheet3.Name) lastRow = .Range("A" & .Rows.Count).End(xlUp).Row For i = 1 To lastRow If .Rows(i).Font.Color = 0 Then If CopyRange Is Nothing Then Set CopyRange = .Rows(i) Else Set CopyRange = Union(CopyRange, .Rows(i)) End If End If Next End With CopyRnge.Copy Destination:=Worksheets("Sheet1").Range("A1:J300") End Sub 

Option Explicit强制你声明你使用的所有variables。

运行程序时CopyRnge.Copy不存在,所以Excel显示运行时错误。

运行时错误1004

像这样的常见错误可以通过默认打开Option Explicit来避免。

如何为VBA中的所有模块启用Option Explicit:

步骤1第2步

build议的代码尝试:

下面的代码使用Option Explicit ,它也利用了对象引用。

通过设置对象引用,您可以依靠智能感知来确保您避免拼写错误。

 Option Explicit Sub CopyBlackText() Dim lastRow As Long Dim i As Long Dim srcRangeToCopy As Range Dim destinationRange As Range Dim wrkbook As Workbook 'Setup Object references by assigning and using the 'Set' keyword Set wrkbook = ActiveWorkbook Set destinationRange = wrkbook.Worksheets("Sheet1").Range("A1:J300") With wrkbook.Worksheets("Sheet3") 'Using Cells(1,1).Address instead of saying Range("A1") lastRow = .Range(Cells(1, 1).Address).End(xlDown).Row For i = 1 To lastRow If .Rows(i).Font.Color = 0 Then If srcRangeToCopy Is Nothing Then Set srcRangeToCopy = .Rows(i) Else Set srcRangeToCopy = Union(srcRangeToCopy, .Rows(i)) End If End If Next End With srcRangeToCopy.Copy Destination:=destinationRange End Sub