簡體   English   中英

自動填充功能打破一項記錄[Excel-VBA]

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM