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

时间:2015-06-13 23:39:13

标签: excel vba excel-vba number-formatting

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

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

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

4 个答案:

答案 0 :(得分:3)

轻松...........将单元格预格式化为文本,然后让事件宏监控单元格并将格式更改为如果输入公式,则常规;然后强制执行公式。例如,单元格 B9

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim B9 As Range
    Set B9 = Range("B9")
    If Intersect(Target, B9) Is Nothing Then Exit Sub

    Application.EnableEvents = False
    With B9
        If Left(.Value, 1) = "=" Then
            .NumberFormat = "General"
            .Value = .Value
        Else
            .NumberFormat = "@"
        End If
    End With
    Application.EnableEvents = True
End Sub

答案 1 :(得分:3)

这是我的版本。

将该表格中的所有单元格格式化为Text。此代码使用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

答案 2 :(得分:1)

条件格式

突出显示您想要影响的范围并单击条件格式。申请如下图所示。您希望将不包含文本“=”的单元格格式化为“text”。

enter image description here

答案 3 :(得分:0)

即使单元格格式设置为“常规”,您也可以通过在数字的开头附加单引号来强制Excel将数字解释为字符串:

ActiveSheet.Cells(1, 1).Value = "'5.80"
'...or...
ActiveSheet.Cells(2, 1).Value = "'" & Format$(58 / 10, "#.00")
相关问题