简体   繁体   中英

put formula in vba based on cell value

I am trying to put a dynamic formula as follows via vba program:

=IFERROR(B9,0)+IFERROR(C9,0)+IFERROR(D9,0)+IFERROR(E9,0)++IFERROR(F9,0)+IFERROR(G9,0)+IFERROR(H9,0)+IFERROR(I9,0)+IFERROR(J9,0)+IFERROR(K9,0)+IFERROR(R9,0)+IFERROR(S9,0)+IFERROR(#REF!,0)+IFERROR(#REF!,0)+IFERROR(#REF!,0)+IFERROR(#REF!,0)+IFERROR(#REF!,0)

I have a cell which stores the number of cols required in the Formula (F3). Now if the value in F3 is 18, what i wish to accomplish is the formula to be in the above format from cell B9 to cell S9 (which is the 19 col, since i start from B to F3+1). Easier to use Sum but that wont serve my purpose. Because if any of the cells in the range in N/A (very much possible), the sum should not be N/A but the sum of rest of the values.

Try This. It will sum and also replace error cell with 0 . It is a very simple loop hence not commented.

Sub SumNumwithoutError()
  Dim rn As Range
  Dim wrn As Range
  Dim xSum As Long
  On Error Resume Next
  xSum = 0
  Set wrn = Application.Selection
  Set wrn = Application.InputBox("Range", wrn.Address, Type:=8)
  For Each rn In wrn
   If (IsError(rn.Value)) Then
        rn.Value = 0
   End If
   If Not (IsError(rn.Value)) Then
       xSum = xSum + rn.Value
   End If
  Next
  MsgBox xSum
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM