[英]Autofill breaks with one record [Excel-VBA]
我的记录从单元格B8开始,我需要从单元格A8开始在A列中对其进行计数。
我使用了这个问题的答案“ 根据相邻列自动填充 ”,但是当recordcount为0或1时该如何处理? 当有1条记录时,它会出错。 似乎自动填充无法自动填充一个单元格。
我有一些条件可以测试零和一,但是有没有更干净的方法呢?
LastRow = Cells(Rows.Count, 2).End(xlUp).Row 'Find last row
If LastRow >= 8 Then 'If recordcount is 1 or greater
Range("A8").FormulaR1C1 = "1" 'First number is "1"
If Not LastRow = 8 Then 'If not recordcount exactly 1
'Enumerate the remaining records with Autofill
Range("A8").AutoFill Destination:=Range("A8:A" & LastRow), Type:=xlLinearTrend
End If
End If
这有两种经过测试的方法可以完成您想做的事情。 第一种方法是您已经在使用的方法,删除妨碍其工作的元素。 第二种是另一种检查方法,因为它可能会为您提供一个具有类似要求的未来项目的想法,但是并不需要使用自动填充功能。
经测试
Sub AutoFiller()
Dim LastRow As Long
LastRow = Cells(Rows.Count, "B").End(xlUp).row 'Find last row
Sheets("Sheet1").Cells(8, 1) = 1 'First number is "1"
Range("A8").AutoFill Destination:=Range("A8:A" & LastRow), Type:=xlLinearTrend
End Sub
使用LOOP代替自动填充:
Sub VBAAutoFill()
Dim LastRow As Long
Dim count As Long
LastRow = Cells(Rows.Count, 2).End(xlUp).Row
count = 1
For lRow = 8 to LastRow
Sheets("Sheet1").Cells(lRow, 1) = count
count = count + 1
Next lRow
end Sub
EXCEL FUNCTION:如果您只想知道总数,则计算所有条目。
COUNTA(B8:B10000)
编辑笔记:详细说明笔记中的过程,纠正错别字。 原始编辑添加的解决方案。
My records start in cell B8, and I need to count them in Column A, starting in cell A8.
我的意思是,您实际上是在枚举行。 这应该有助于解决您的错误问题,并且如果它与A
列中所A
的不完全相同,那么您就不难进行调整了:
Public Sub GetRangeCount()
Dim bRange As Range
Set bRange = Range(Range("B8"), Range("B1048575").End(xlUp))
Dim i As Integer
i = 0
For Each c In bRange
If c.Value <> "" Then
i = i + 1
c.Offset(0, -1).Value = i
End If
Next
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.