简体   繁体   English

在VBA中的单元格中替换公式

[英]Replace Formula in a cell in VBA

I have a cell of C6 , it's current value is formula of C5/C4 , I want to change the formula to If(C4=0, 0, C5/C4) . 我有一个C6单元格,它的当前值为C5/C4的公式,我想将该公式更改为If(C4=0, 0, C5/C4)

I have many cells similar to this cell, that's why I want to develop a macro so I can loop through them. 我有很多与此单元格相似的单元格,这就是为什么我想开发一个宏以便可以遍历它们的原因。

However, the code below does not work. 但是,下面的代码不起作用。 I think the problem is Divider=0 in the last line. 我认为问题是最后一行的Divider=0 Because if I replace this part directly with C4=0 , the code will work. 因为如果我直接将这部分替换为C4=0 ,那么代码将起作用。

can someone advise me what would be the correct code? 有人可以告诉我正确的代码是什么吗? Thanks in advance! 提前致谢!

Sub replaceingError()

  Dim ws As Worksheet
  Set ws = ActiveSheet
  Dim StrTemp As String
  Dim Divider As String
  StrTemp = ws.Range("c6").formula
  MsgBox (StrTemp) 
  Divider = Right(StrTemp, 2)
  MsgBox (Divider)
  ws.Range("c6").value = "=IF(Divider=0, 0, strTemp)"

End Sub

You can't use .Value to set formula 您不能使用.Value设置公式

Correct syntax is .Formula 正确的语法是.Formula

ws.Range("c6").Formula = "=IF(" & Divider & "=0, 0, strTemp)"

You have to make a concatenation of the new formula parts with variables value: 您必须将新的公式部分与变量value串联起来:

Sub replaceingError()

    Dim oWS As Worksheet
    Dim sTemp As String
    Dim sDivider As String
    Dim sFormula As String

    Set oWS = ActiveSheet
    sTemp = oWS.Range("C6").Formula
    sDivider = Right(sTemp, 2)
    sTemp = Mid(sTemp, 2)
    sFormula = "=IF(" & sDivider & "=0,0," & sTemp & ")"
    oWS.Range("C6").Formula = sFormula

End Sub

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

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