2025年11月2日 星期日

VBA 資料分析教學:Day 3

 此範例示範如何用VBA在Excel工作表中計算某一範圍內數字的平均值,並在欄位中標示出大於平均值的儲存格,使分析更直觀。適合初學者了解循環與條件判斷。

VBA 程式碼:

Sub 標示超過平均值的數字()

    Dim rng As Range

    Dim cell As Range

    Dim total As Double

    Dim count As Long

    Dim avgValue As Double

    

    ' 設定目標範圍(假設為A1:A10)

    Set rng = Range("A1:A10")

    

    total = 0

    count = 0

    

    ' 計算總和及數量

    For Each cell In rng

        If IsNumeric(cell.Value) And Not IsEmpty(cell.Value) Then

            total = total + cell.Value

            count = count + 1

        End If

    Next cell

    

    ' 計算平均值

    If count > 0 Then

        avgValue = total / count

    Else

        MsgBox "範圍內無有效數值"

        Exit Sub

    End If

    

    ' 標示大於平均值的儲存格

    For Each cell In rng

        If IsNumeric(cell.Value) And cell.Value > avgValue Then

            cell.Interior.Color = RGB(255, 255, 0) ' 黃色填滿

        Else

            cell.Interior.ColorIndex = 0 ' 清除色彩

        End If

    Next cell

    

    MsgBox "平均值為:" & avgValue

End Sub


說明:

用 For Each 迴圈遍歷指定範圍的儲存格

判斷儲存格是否為數字且非空白

計算平均值後,比較每個儲存格的值,並標示大於平均值者

適合快速視覺化資料分析結果


沒有留言:

張貼留言

集保整理 15周內股價高點千張大戶減持或不變 20251205

這裡的做夢資料千萬別當真。 -------------------------------------------------------- 8431 匯鑽科 周三大法人持股對比千張大戶 千張大戶 周三大法人持股 River's Footmar And Note 2024...