gpt4 book ai didi

vba - 将包含行的范围复制到另一个工作表

转载 作者:行者123 更新时间:2023-12-04 21:05:27 25 4
gpt4 key购买 nike

我的要求是将具有黑色字体颜色的 sheet3 中的行复制到 sheet1。我在工作簿中从 sheet3 中选择了一系列行。我想复制它并粘贴到 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强制您声明您使用的所有变量。
CopyRnge.Copy运行程序时不存在,因此 Excel 显示运行时错误。

Run-time error 1004

开启 Option Explicit 可以避免此类常见错误。默认。

如何为 VBA 中的所有模块启用选项显式:

Step 1
Step 2

建议尝试代码:

下面的代码使用 Option Explicit它还利用了使用对象引用的优势。

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

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

关于vba - 将包含行的范围复制到另一个工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22321329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com