vba - Numberformat 允许我输入公式但将值存储为文本?

标签 vba excel number-formatting

是否可以使用 Excel 或 VBA 在单元格/列中设置数字格式,以便:

  • 如果我输入一个公式(任何以 = 开头的内容),Excel 将计算公式(而不是将其解释为文本)
  • 如果我输入一个值,例如 5.80,Excel 会将其存储为文本吗?

我遇到一个问题,我希望所有用户输入都存储为文本,但用户也应该能够输入公式。如果我将数字格式设置为文本,则不会解释公式。如果我将数字格式设置为常规,则值将存储为数字。

最佳答案

这是我的版本。

将该工作表中的所有单元格格式设置为文本。此代码使用 Application.Evaluate() 计算所有公式并将结果存储为文本。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim aCell As Range

    On Error GoTo Whoa

    Application.EnableEvents = False

    '~~> You need this in case user copies formula
    '~~> from another sheet
    Target.Cells.NumberFormat = "@"

    '~~> Looping though all the cells in case user
    '~~> copies formula from another sheet
    For Each aCell In Target.Cells
        If Left(aCell.Formula, 1) = "=" Then _
        aCell.Value = Application.Evaluate(aCell.Formula)
    Next

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

关于vba - Numberformat 允许我输入公式但将值存储为文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30824630/

相关文章:

excel - 制作宏以将数据输入到 Excel 电子表格中

VBA excel从工作表复制公式并粘贴到多个工作表

Excel VBA - 从代码中读取单元格值

excel - VBA 全局变量

c++ - 将十六进制转换为带符号的十进制

excel - Excel 的日期轴标记算法

excel - 检索Excel中重复项之间最大日期的单元格值

c# - 如何在 EPPlus C# 中使 Excel 列只读但可调整大小?

ios - 如何获取带小数的格式数字(XCode)

javascript - Intl.NumberFormat 在 Jest 单元测试中表现不正确?