返回列表 上一主題 發帖

[分享] 以欄號 計整欄多少數字 (14532)

底下是請我隔壁鄰居ChatGPT幫我寫的程式碼

Sub CountNumbersInColumns()

    Dim ws As Worksheet
    Dim lastRow As Long, lastCol As Long
    Dim r As Long, c As Long
    Dim countNum As Long
    Dim outCol As Long
    Dim outRow As Long
    Dim colLetter As String
   
    Set ws = ActiveSheet

    '自動偵測整張工作表真正的最後列
    lastRow = ws.Cells.Find(What:="*", _
                            LookIn:=xlFormulas, _
                            LookAt:=xlPart, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious).Row

    '自動偵測整張工作表真正的最後欄
    lastCol = ws.Cells.Find(What:="*", _
                            LookIn:=xlFormulas, _
                            LookAt:=xlPart, _
                            SearchOrder:=xlByColumns, _
                            SearchDirection:=xlPrevious).Column

    '輸出從資料右側兩欄開始
    outCol = lastCol + 2
    outRow = 2 '從第 2 列開始輸出(第 1 列保留當表頭)

    '清除舊資料
    ws.Columns(outCol).Resize(, 2).ClearContents

    '表頭
    ws.Cells(1, outCol).Value = "欄號"
    ws.Cells(1, outCol + 1).Value = "結果"

    '逐欄統計
    For c = 1 To lastCol
        countNum = 0

        For r = 1 To lastRow
            If IsNumeric(ws.Cells(r, c).Value) And ws.Cells(r, c).Value <> "" Then
                countNum = countNum + 1
            End If
        Next r

        '若結果為 0,跳過不輸出
        If countNum > 0 Then

            '取得欄字母,例如 "C"
            colLetter = Replace(Split(ws.Cells(1, c).Address(False, False), "$")(0), "1", "")

            '輸出
            ws.Cells(outRow, outCol).Value = colLetter
            ws.Cells(outRow, outCol + 1).Value = countNum

            outRow = outRow + 1
        End If
    Next c

    MsgBox "統計完成!", vbInformation
End Sub

TOP

        靜思自在 : 屋寬不如心寬。
返回列表 上一主題