选择范围对象(VBA)中每个单元格的行



我正试图将一系列数据从一个工作表复制到另一个。范围由A列中与设定值匹配的值定义。我可以将具有指定值的每个单元格添加到范围对象中,但现在我必须选择范围对象中单元格行中的所有数据,才能将它们复制到另一个工作表中。有什么建议吗?

此外,我对VBA很陌生,所以我确信我的代码格式很糟糕,但我真的只需要一个解决这个特殊问题的方案。谢谢你的帮助!

Dim allAsNum As Range
Dim currAsNum As Range
Dim asnum
Dim j
Sheets("Full Log").Select
asnum = "searchingvalue"
For j = 2 To CInt(Cells(Rows.Count, "A").End(xlUp).Row)
If Range(Sheets("Full Log").Cells.Address).Cells(j, 1).Value = asnum Then
If allAsNum Is Nothing Then
Set allAsNum = Range(Sheets("Full Log").Cells.Address).Cells(j, 1)
Else
Set allAsNum = Union(allAsNum, Range(Sheets("Full Log").Cells.Address).Cells(j, 1))
End If
End If
Next j

Set currAsNum = allAsNum.Rows 'This is the line that I can't figure out
currAsNum.Select
Scott Craner是对的。然而,对您的代码的一些备注

a( 初学者并不是不缩进代码的借口。只需遵循规则,在每个SubIfForWith-语句的缩进级别上添加1(此列表并不完整,但您已经明白了(。在匹配的End-语句中减去1。对每个缩进使用<TAB>

b( 不要使用select。如何避免在Excel VBA 中使用Select的强制链接

c( 您使用正确的技术来获得最后一行。但是,这已经返回了一个Long值,不需要使用CInt强制转换它。出于调试原因,最好在使用之前将其写入变量中。顺便说一下,您应该将变量j声明为Long(也许可以考虑一个更好的名称(。

d( 你读取单元格的技术是有效的,但不必要地复杂。简单使用Cells(j, 1)

代码可能如下所示:

Const asnum = "searchingvalue"
Dim allAsNum As Range
Dim rowCount as long, curRow as long
With ThisWorkbook.Sheets("Full Log")   
rowCount = .Cells(.Rows.Count, "A").End(xlUp).Row
For curRow = 2 To rowCount 
If .Cells(curRow , 1).Value = asnum Then
If allAsNum Is Nothing Then
Set allAsNum = .Cells(curRow, 1)
Else
Set allAsNum = Union(allAsNum, .Cells(curRow, 1)) 
End If
End If
Next curRow 
End With
' (The destination of the following copy needs to be adapted to your needs)
allAsNum.EntireRow.Copy ThisWorkbook.Sheets("Sheet1").Range("A1")

最新更新