简体   繁体   English

Excel宏用于向具有公式的单元格添加值

[英]Excel macro to add value to a cell with a formula

I am trying to set up a macro to add a value, say 10, to an existing cell that has a formula in it. 我正在尝试设置一个宏来将值(例如10)添加到其中包含公式的现有单元格中。 I would like the cell to maintain the formula. 我希望细胞保持配方。

Here is what I've done so far: 这是我到目前为止所做的:

Sub addvalue 
'Keyboard Shortcut: Ctrl+Shift+A

ActiveCell.Formula = ActiveCell.Formula + 10

End Sub

This isn't working for me. 这不适合我。 It works when the cell is just a number, but not when the cell I am trying to adjust is a formula. 当单元格只是一个数字时,它可以工作,但是当我试图调整的单元格是公式时,它不起作用。

If the cell I'm trying to adjust contains =A1 + 4 and I run this macro, I'd like it to be =A1 + 14 after the macro runs. 如果我正在尝试调整的单元格包含=A1 + 4并运行此宏,我希望它在宏运行后为=A1 + 14

getting to change the formula itself is problematic. 改变公式本身是有问题的。 but you can append the +10 to the end and get =A1 + 4 + 10 with: 但你可以将+10追加到最后并获得=A1 + 4 + 10

ActiveCell.Formula = ActiveCell.Formula & "+ 10"

The issue is that ActiveCell.Formula returns a string and you cannot add a number to a string. 问题是ActiveCell.Formula返回一个字符串,你不能在字符串中添加一个数字。 You need to concatenate the string and the new part. 您需要连接字符串和新部分。


Edit 编辑

To make it so it changes the value instead of concatenating: 为了使它改变值而不是连接:

Sub addvalue()
'Keyboard Shortcut: Ctrl+Shift+A
Dim strsplit() As String
Dim i As Long
Dim dn As Boolean


dn = False

strsplit = Split(Mid(ActiveCell.Formula, 2), "+")
For i = LBound(strsplit) To UBound(strsplit)

    If IsNumeric(strsplit(i)) Then
        strsplit(i) = CDbl(strsplit(i)) + 10
        dn = True
        Exit For
    End If
Next i

ActiveCell.Formula = "=" & Join(strsplit, "+") & IIf(dn, "", "+ 10")

End Sub

This may not work in all cases but for simple formulas it does. 这可能不适用于所有情况,但对于简单的公式它可以。

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

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