2017-08-14 58 views
1

我试图使用VBA在列“A”中自动填充(1,2,3,...),同时跳过非空白/空的行。例如,如果在“A3”和“A5”的文本/数据,代码将计算如下:只在空白(空)单元格中按数字顺序计数

"A1" = 1    "B1" = text/data 
"A2" = 2    "B2" = text/data 
"A3" = text/data  "B3" = text/data 
"A4" = 3    "B4" = text/data 
"A5" = text/data  "B5" = text/data 
"A6" = 4    "B6" = text/data 
"A7" = 5    "B7" = text/data 

...等等

到目前为止,我只能够跳过之前输入的文本行,但该计数继续,因为它不会跳过任何单元格。

请注意:我在列“B”中使用.End(xlDown).Count来定义计数器应该走多远。

这是我迄今为止

Sub Counter() 

Dim NoF As Long 
Dim Test As Long 

NoF = Range("B1", Range("B1").End(xlDown)).Count 

For i = 1 To NoF 

    If Cells(i, 1) = "" Then 
     ActiveSheet.Cells(i, 1).Value = i 
    ElseIf Cells(i, 1) <> "" Then 
     ActiveSheet.Cells(i, 1).Offset(i + 1, 1).Select 
    End If 

Next i 

End Sub 

回答

0

你可以使用它与文本计数行的第二个变量。在for循环之外初始化为零,如果有一些文本,则加1。接下来,你只需要从i中减去它。

j = 0 
For i = 1 To NoF 

    If Cells(i, 1) = "" Then 
     ActiveSheet.Cells(i, 1).Value = i - j 
    ElseIf Cells(i, 1) <> "" Then 
     ActiveSheet.Cells(i, 1).Offset(i + 1, 1).Select 
     j = j + 1 
    End If 

Next i 

你不需要Offset,该作品,以及

Option Explicit 

Sub Counter() 

Dim NoF As Long 
Dim j As Long 
Dim i As Long 

NoF = Range("B1", Range("B1").End(xlDown)).Count 
j = 0 

For i = 1 To NoF 

    If Cells(i, 1) = "" Then 
     Cells(i, 1).Value = i - j 
    Else 
     j = j + 1 
    End If 

Next i 

End Sub 
+0

嗨@ Capema00如果这个或任何答案已经解决你的问题,请考虑[接受它(https://开头meta.stackexchange.com/q/5234/179419)点击复选标记。这向更广泛的社区表明,您已经找到了解决方案,并为答复者和您自己提供了一些声誉。没有义务这样做。 upvoting也是一样。 – PalimPalim