0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Excel VBA】Sgn関数|数値の正負を判定して符号を返す方法と注意点

Last updated at Posted at 2025-08-21

この記事ではSgn関数の使い方と注意点について解説します。
他のよく使うVBA関数一覧はこちら。

Sgn関数の使い方と注意点

Sgn関数は、数値の符号を調べて -1, 0, 1 のいずれかを返す関数です。
数値が正か負かを判定する処理に便利です。

構文

Sgn(数式)
  • 数式 : 評価対象となる数値式。数値以外を渡すとエラー。
  • 戻り値 : 正負を表す整数値

戻り値の種類

戻り値 意味 条件
1 数式>0
0 ゼロ 数式=0
-1 数式<0

使用例

正の数を判定

Sub Sample()
    Debug.Print Sgn(10)
End Sub

▶ 出力結果

1

負の数を判定

Sub Sample()
    Debug.Print Sgn(-8)
End Sub

▶ 出力結果

-1

ゼロの場合

Sub Sample()
    Debug.Print Sgn(0)
End Sub

▶ 出力結果

0

変数で判定

Sub Sample()
    Dim MyVal As Double
    
    MyVal = -2.34
   
    If Sgn(MyVal) = -1 Then
        Debug.Print MyVal & "は負の値"
    End If
End Sub

▶ 出力結果

-2.34は負の値

⚠️注意

Nullや文字列を渡すとエラーになる

Sgn(Null)Sgn("abc") はエラーになります。
事前にIsNumericIsNullでチェックしておくと安全です。

Sub Sample()
    Dim MyArray(4) As Variant
    Dim CheckSgn As Integer
    
    MyArray(0) = 10
    MyArray(1) = -2.34
    MyArray(2) = 0
    MyArray(3) = "abc"
    MyArray(4) = Null
    
    For i = 0 To UBound(MyArray)
        If IsNull(MyArray(i)) Then
            Debug.Print i & " : " & "Nullです"
        Else
            If IsNumeric(MyArray(i)) Then
                CheckSgn = Sgn(MyArray(i))
                If CheckSgn = 1 Then
                    Debug.Print i & " : " & MyArray(i) & " : 正の値です"
                ElseIf CheckSgn = 0 Then
                    Debug.Print i & " : " & MyArray(i) & " : ゼロです"
                Else
                    Debug.Print i & " : " & MyArray(i) & " : 負の値です"
                End If
            Else
                Debug.Print i & " : " & MyArray(i) & " : 数値以外です"
            End If
        End If
    Next i
End Sub

▶ 出力結果

0 : 10 : 正の値です
1 : -2.34 : 負の値です
2 : 0 : ゼロです
3 : abc : 数値以外です
4 : Nullです

その他のVBA関数

【Excel VBA】VBAでよく使う関数一覧&基本の使い方

参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?