vba - 循环单元格并添加到范围

标签 vba excel

如果单元格 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 every 循环比 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
    

关于vba - 循环单元格并添加到范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8320822/

相关文章:

excel - 如何在不循环的情况下计算数据透视表特定字段中的可见项目?

excel - 如何选择特定的 SAP GUI session ?

python - 如何将空可选参数从 Python 传递到 Excel VBA 宏

vba - 如果整列颜色为红色,则在 VBA 中查找列号

html - 导航到 VBA 中的页面后无法重置 HTML 文档

vba - 如何比较工作表中的两整行

excel - 柯拉兹猜想。找到最小的 a_k

excel - vba listobject CopyFromRecordset

python - 使用Python或Excel vba将单个Excel单元格内容拆分为不同的单元格

excel - 在vba中使用AND条件