masatoの日記

やっていきます

ExcelのオートSUMを補完するSuperオートSUMをつくった

Excelで一番よく使う関数、それはSUM(たぶん)。
しかし、これには弱点がある。途中で空行があると合計がそこで途絶えてしまうのだ。

そんなとき、結局手動でSUMを打ち込み、セルを選択しているのではないだろうか。

組み込み関数の限界なのかもしれない。

そこで、Excel VBAだ。

開始行を自動判定するのが大変なので、そこはユーザーに指定してもらうことにした。終了行も一応、同様に指定するようにしている。

sub SuperAutoSUM()
    Dim startRow As Long
    startRow = InputBox("開始行数を指定...")
    
    Dim endRow As Long
    endRow = InputBox("終了行数を指定...")
    
    If startRow = 0 Or endRow = 0 Then Exit Sub
    
    Dim currCol As Long
    currCol = ActiveCell.column
    If currCol = 0 Then
        MsgBox "対象の列を選択してください。"
        Exit Sub
    End If
    
    Dim i As Long
    Dim addresses As String
    For i = startRow To endRow
        Dim r As Range
        Set r = cells(i, currCol)
        If Not r Is Nothing Then
            If r.Value <> "" Then
                addresses = addresses & "," & r.Address
            End If
        End If
    Next
    '左端の“,”を削除する
    addresses = Right$(addresses, len(addresses) -1)
    
    Dim formulaStr As String
    formulaStr = "=sum(" & addresses & ")"
    ActiveCell.Formula = formulaStr
End Sub

なんとなく便利かもと思って書いたが、実際にはあまり使っていない...