Using VBA to check if below cell is empty

前端 未结 3 1647
半阙折子戏
半阙折子戏 2020-12-07 00:42

How do I use VBA in Excel to check if a below cell is empty or not? I want to sum all values in a specific range, but only, if the below cell is not empty.

Is that s

3条回答
  •  感情败类
    2020-12-07 01:37

    I would recommend a Formula for this

    FORMULA

    =SUMPRODUCT((A1:E1)*(A2:E2<>""))
    

    SNAPSHOT

    enter image description here

    If you still want VBA then

    VBA

    Option Explicit
    
    Sub Sample()
        Dim rng As Range
        Dim Cl As Range
        Dim tot As Long
    
        Set rng = Range("A1:F1")
    
        For Each Cl In rng
            If Len(Trim(Cl.Offset(1))) <> 0 Then tot = tot + Cl.Value
        Next
    
        Debug.Print tot
    End Sub
    

    In fact you can have many versions in VBA. You can evaluate the above formula as well. For example

    Option Explicit
    
    Sub Sample()
        Debug.Print Evaluate("=SUMPRODUCT((A1:E1)*(A2:E2<>""""))")
    End Sub
    

提交回复
热议问题