How to rewrite excel formulas in a readable manner?

前端 未结 9 2571
萌比男神i
萌比男神i 2021-02-13 02:53

I have an Excel file with formulas in this manner:

=IF(OR(ISERROR(G16),ISERROR(G17)),X16,IF(OR(G16=\"xxx\",G16=\"yyy\",G16=\"zzz\"),Y16,IF(G16=\"333\",\"N\\A\",IF(

9条回答
  •  清歌不尽
    2021-02-13 03:16

    Since you asked about VBA code, I thought I'd give it a try. It's certainly more understandable and therefore maintainable, however the function has 11 arguments so it's a little unwieldy.

    Function Magic(d17 As Range _
                    , f16 As Range _
                    , g16 As Range _
                    , g17 As Range _
                    , w10 As Range _
                    , w16 As Range _
                    , w17 As Range _
                    , x16 As Range _
                    , y16 As Range _
                    , z16 As Range _
                    , m36 As Range) As Variant
    
    
        Dim a As Variant
        Dim b As Variant
    
        If IsError(g16.Value) Or IsError(g17.Value) Then
            Magic = x16.Value
            Exit Function
        End If
    
        If g16.Value = "xxx" Or g16.Value = "yyy" Or g16.Value = "zzz" Then
            Magic = y16.Value
            Exit Function
        End If
    
        If g16.Value = "333" Then
            Magic = "N\A"
            Exit Function
        End If
    
        If g17.Value = "333" Then
            Magic = z16.Value
            Exit Function
        End If
    
        If d17.Value = "" Then
            a = Application.WorksheetFunction.Hex2Dec(w10.Value) _
                    - Application.WorksheetFunction.Hex2Dec(w16.Value)
            a = a / Application.WorksheetFunction.VLookup(f16.Value, m36, 2, False)
            If a < 0 Then
                Magic = 0
                Exit Function
            Else
                Magic = a
                Exit Function
            End If
        Else
            b = Application.WorksheetFunction.Hex2Dec(w17.Value) _
                    - Application.WorksheetFunction.Hex2Dec(w16.Value)
            b = b / Application.WorksheetFunction.VLookup(f16.Value, m36, 2, False)
            If b < 0 Then
                Magic = 0
                Exit Function
            Else
                Magic = b
                Exit Function
            End If
        End If
    End Function
    

    To make it easier to follow your formula logic (and I didn't know what the cells represent), I named the variables for the cell references. You'll want to rename them to something meaningful. The code belongs in a module.

提交回复
热议问题