循环访问使用条件select的非连续行

这是我在SO的第一篇文章。 如你所知,我不是一个专业的程序员,只是一个普通的办公室工作人员不时地做一些VBA来加快他的工作。

我想循环使用VBA的单元格范围,在其中的一列中包含特定的标志值。 这些范围是非连续的,因为我们select具有连续标志值的范围,并且该值在每一行中随机地改变。

例如在下面的表格中,我们如何循环三次(因为有三个不连续的范围和连续的-1个标志),select第一次迭代中的前三行,第二次中的第五和第六行,第三次迭代中的第八行?

+-------+---------+------+ | Index | Value | Flag | +-------+---------+------+ | 1 | 0.43534 | -1 | | 2 | 0.24366 | -1 | | 3 | 0.23654 | -1 | | 4 | 0.56854 | 0 | | 5 | 0.97867 | -1 | | 6 | 0.35678 | -1 | | 7 | 0.47845 | 0 | | 8 | 0.74567 | -1 | +-------+---------+------+ 

以下代码将在消息框中给出结果,指定Flag = -1所有范围。 根据您的样本数据图像,输出将是$C$2:$C$4$C$6:$C$7$C$9

 Sub Demo() Dim ws As Worksheet Dim cel As Range, rng As Range, fCell As Range, tempRng As Range Dim lastRow As Long Dim isNegative As Boolean Set ws = ThisWorkbook.Sheets("Sheet2") 'change Sheet2 to your data sheet isNegative = False With ws lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row 'last row with data in Column C For Each cel In .Range("C2:C" & lastRow + 1) 'loop through each cell in Column C If cel.Value = -1 Then 'check if value is -1 If Not isNegative Then Set fCell = cel isNegative = True End If Else 'if not then set range If isNegative Then If rng Is Nothing Then Set rng = .Range(fCell, cel.Offset(-1, 0).Address) Else Set rng = Union(rng, .Range(fCell, cel.Offset(-1, 0).Address)) End If isNegative = False End If End If Next cel End With For Each tempRng In rng.Areas 'loop through all ranges with -1 MsgBox tempRng.Address 'write your code here Next tempRng End Sub 

下面是对代码中使用的BooloeanvariablesisNegative的简要说明。

isNegative用于维护标志范围.Range("C2:C" & lastRow + 1)中的最后一个单元格值是否为-1 ,并且在开始时设置为FALSE 。 当第一个-1被反击时, isNegative被设置为TRUE并且fCell被分配相应的单元地址。 直到遇到-1isNegative将保持为TRUE 。 当遇到值不等于-1单元格时,使用Set rng = .Range(fCell, cel.Offset(-1, 0).Address)如果只有一个单元格带有-1如果遇到多于一个具有-1单元格,则会遇到另一个Set rng = Union(rng, .Range(fCell, cel.Offset(-1, 0).Address))
当遇到第二个或更多个值不等于-1连续单元格时,则不会发生任何事情。 当遇到下一个值为-1单元格时,重复上述过程。

你仍然可以像平常一样循环,但是使用If语句来检查第3列(C)是否有-1,例如:

 Dim i as Long For i = 2 to 9 'Assumes 1 is a header row, despite 1-8 being counted If Cells(i,3).Value= -1 Then 'Do something End If Next i 

我会考虑使用类似的东西do while flag=-1

或者, if Flag(index)=Flag(index+1) then *do something*使用条件if Flag(index)=Flag(index+1) then *do something* ,因为我认为更复杂的事情需要devise一个模块类。