我正在尝试设置一个宏来向其中包含公式的现有单元格添加一个值(例如 10)。我希望细胞能够维持公式。
这是我到目前为止所做的事情:
Sub addvalue
'Keyboard Shortcut: Ctrl+Shift+A
ActiveCell.Formula = ActiveCell.Formula + 10
End Sub
这对我不起作用。当单元格只是一个数字时它有效,但当我尝试调整的单元格是一个公式时它不起作用。
如果我尝试调整的单元格包含 =A1 + 4
并且我运行此宏,我希望在宏运行。
最佳答案
改变公式本身是有问题的。但您可以将 +10
附加到末尾并获得 =A1 + 4 + 10
:
ActiveCell.Formula = ActiveCell.Formula & "+ 10"
问题是 ActiveCell.Formula
返回一个字符串,并且您无法将数字添加到字符串中。您需要连接字符串和新部分。
编辑
要使其更改值而不是连接:
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
这可能并不适用于所有情况,但对于简单的公式却适用。
关于vba - Excel 宏使用公式为单元格添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46451373/