VBA除以1000而不删除公式

时间:2018-11-26 12:26:10

标签: excel vba excel-vba

我目前正在使用此基本代码将单元格的值除以1000:

Sub Divide_by_1000()
    Dim cell As Range
    For Each cell In Selection
        cell = cell / 1000
    Next
End Sub

虽然它对于硬编码数字非常有效,但是如果用于其中有公式的单元格,它会删除该公式并输出数字。

理想情况下,我希望宏能够像在其中具有数字的单元格一样工作,但是对于具有公式的单元格,我希望它在当前公式周围用括号括起来并放在/1000周围最后(即保持公式完好无损)

我相信需要进行测试,以首先检查单元格中是否包含公式,如果没有,则应用我已经拥有的代码,如果有,则应用我上面概述的代码。

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:5)

您可以通过检查第一个字符是否为等号=

来检查单元格是否具有公式
If Left$(cell.Formula, 1) = "=" Then

甚至更好

If cell.HasFormula Then

,然后重写由( … )/1000扩展的公式

cell.Formula = "=(" & Right$(cell.Formula, Len(cell.Formula) - 1) & ")/1000"

我还建议在除以1000之前先检查cell.Value是否为数字

ElseIf IsNumeric(cell.Value) Then
   cell.Value = cell.Value / 1000

所以您最终会得到类似的东西

If Left$(cell.Formula, 1) = "=" Then
    cell.Formula = "=(" & Right$(cell.Formula, Len(cell.Formula) - 1) & ")/1000"
ElseIf IsNumeric(cell.Value) Then
    cell.Value = cell.Value / 1000
End If

请注意,虽然这适用于常规公式,但会破坏数组公式。

答案 1 :(得分:3)

@PEH发表评论后:

您可以使用from flask import Flask, Response, jsonify import werkzeug app = Flask(__name__) @app.route("/") def hello(): def generate(): raise Exception yield '1' try: generator = generate() return Response(next(generator)) except Exception: return jsonify("error") if __name__ == '__main__': app.run() .HasFormula来测试公式类型

.HasArray

答案 2 :(得分:1)

可以使用HasFormula属性检查范围/单元格中的公式,例如

Dim TheArea as range
Set TheArea = range("some name")

If TheArea.HasFormula then
    '  All the cells in the range have a formula
End if

或者,您可以使用某个范围的specialcells属性,例如

For Each Cell In TheArea.SpecialCells(xlCellTypeConstants)
    Cell.Value = cell.Value/1000
Next Cell

For Each Cell In TheArea.SpecialCells(xlCellTypeFormulas)
    Cell.Formula = "=(" & Right$(Cell.Formula, Len(Cell.Formula) - 1) & ")/1000"
Next Cell

这种方法还使您有机会检测其他可能的情况,例如xlCellTypeBlanks,如果它们对您很重要。特殊单元的完整列表可以在这里找到...

https://docs.microsoft.com/en-us/office/vba/api/excel.range.specialcells