像您那样改变范围会变

时间:2019-07-01 20:46:34

标签: excel vba

比方说,我想使用CountA(RangeFrom:RangeTo)函数来查看单元格区域中是否有任何数据。是否可以使RangeFrom和RangeTo成为变量?我想下一张纸签出一个20x20的框,然后循环到它下面的下一个20x20框,其中的单元格之间充满文本。但是,我不知道如何将变量放入CountA函数中,或者是否有可能使我可以跳过充满文本的单元格所在的行。如果有办法,我可能措词不正确,导致找不到任何有关它的信息。任何帮助将不胜感激。

此刻,我正在使用行和列遍历整个代码,并只是逐个检查每个单元格,我想知道是否可以将CountA与变量一起使用。

Dim RowCounter As Integer
Dim ColumnTraversing As Integer
Dim PopulatedCounter As Integer 
Dim OverallCounter As Integer
RowCounter = 1
PopulatedCounter = 0

While (OverallCounter < 5) 
    ColumnTraversing = 1
    With ThisWorkbook.Worksheets("Test") 
       While (ColumnTraversing <= 6)'column looper

           While (RowCounter <= 40) 'Row Looper
 '
               If (.Cells(RowCounter, ColumnTraversing).Text <> "") Then
                   i = i + 1
               End If
               RowCounter = RowCounter + 1
           Wend

           ColumnTraversing = ColumnTraversing + 1
           RowCounter = 1
        Wend
        If (i > 0) Then 
            PopulatedCounter = PopulatedCounter + 1
        End If
    End With
    OverallCounter = OverallCounter + 1
    i=0
    RowCounter = RowCounter + 2

Wend 

这会循环通过一个6x40的框,然后向下移动并再次检查它是否已填充,本质上是执行CountA函数的操作,但要覆盖多个变量。

1 个答案:

答案 0 :(得分:1)

根据上面的评论,我假设您要循环浏览40行* 6列并由包含文本的一行分隔的框。我们可以这样循环:

Sub Macro1()
Dim iRow As Integer, PCounter As Integer, numBoxes as Integer
iRow = 1: PCounter = 0: numBoxes = 0 'numBoxes counts the number of Boxes down the sheet

While (numBoxes <= 5) 'Change this to the number of boxes you have
    With ThisWorkbook.Worksheets("Test")
        PCounter = PCounter + WorksheetFunction.CountA(.Range("A" & iRow & ":F" & iRow + 39))
        iRow = iRow + 41 ' 41 = 40 rows of boxes + 1 row of text between bixes
    End With
    numBoxes = numBoxes + 1
Wend

End Sub