[英]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
來粘合你的范圍
For each
循環都比For i = 1 to x
方法快 您可以使用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.