繁体   English   中英

循环遍历单元格并添加到范围

[英]Loop through cells and add to a range

如果它们符合某个标准,我将如何遍历单元格B1到J1并将它们添加到范围中。 例如。

Dim Range1 As Range
For i = 1 to 9
If Range("A1").Offset(1,i) meets a certain criteria Then
**Add that cell to Range1**
End If
Next i

我不确定如何处理向Range1添加某些单元格的部分。

谢谢您的帮助!

像这样使用Union来粘合你的范围

  1. 请注意, For each循环都比For i = 1 to x方法快
  2. 您可以使用SpecialCells立即确定您的新范围(例如任何空白,任何错误,任何公式等)

     Sub Test() Dim rng1 As Range Dim rng2 As Range Dim c As Range Set rng1 = Range("B1:J1") For Each c In rng1 ' Add cells to rng2 if they exceed 10 If c.Value > 10 Then If Not rng2 Is Nothing Then ' Add the 2nd, 3rd, 4th etc cell to our new range, rng2 ' this is the most common outcome so place it first in the IF test (faster coding) Set rng2 = Union(rng2, c) Else ' the first valid cell becomes rng2 Set rng2 = c End If End If Next End Sub 

当我不想在表单中添加代码时,我在立即模式下使用此方法。

strX="": _
For Each cllX in Range( ActiveCell, Cells( Cells.SpecialCells(xlCellTypeLastCell ).Row, ActiveCell.Column) ): _
strX=strX & iif(cllX.text="","",iif(strX="","",",")& cllX.address): _
Next: _
Range(strX).Select

虽然这很直观,但它只适用于35到50个细胞。 之后,VBA返回错误1004。

Run-time error '1004':
Application-defined or object-defined error

使用Union功能更加健壮。

Set rngX=ActiveCell: _
For Each cllX in Range( ActiveCell, Cells( cells.SpecialCells(xlCellTypeLastCell ).Row, ActiveCell.Column) ): _
Set rngX=iif( cllX.text="", rngX, Union(rngX, cllX) ): _
Next: _
rngX.Select

它是如此简短和直观,我只是在每次使用后丢弃它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM