简体   繁体   English

根据单元格值将公式放入 vba

[英]put formula in vba based on cell value

I am trying to put a dynamic formula as follows via vba program:我正在尝试通过 vba 程序放置如下动态公式:

=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).我有一个单元格,用于存储公式(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).现在,如果 F3 中的值是 18,我希望完成的是从单元格 B9 到单元格 S9(这是 19 col,因为我从 B 开始到 F3+1)的上述格式的公式。 Easier to use Sum but that wont serve my purpose.更容易使用 Sum 但这不会达到我的目的。 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.因为如果 N/A 范围内的任何单元格(很有可能),总和不应该是 N/A,而是其余值的总和。

Try This.尝试这个。 It will sum and also replace error cell with 0 .它将求和并用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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