Numberformat允许我input公式,但将值存储为文本?
是否可以使用Excel或VBA在单元格/列中设置numberformat,以便:
- 如果我input一个公式(任何以=开头的东西),Excel将计算公式(而不是仅仅将其解释为文本)
- 如果我input一个值,例如5.80,Excel将它存储为文本?
我有一个问题,我希望所有的用户input被存储为文本,但用户也应该能够input公式。 如果我将数字格式设置为文本,公式不解释。 如果我将数字格式设置为常规,则数值将以数字forms存储。
这是我的版本。
将该表格中的所有单元格设置为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
简单………预先格式化单元格为文本 ,然后有一个事件macros监视单元格,并将格式更改为常规,如果input一个公式; 然后强制执行公式。 例如单元格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
条件格式
突出显示您想要受影响的范围并单击条件格式。 如下所示应用。 您希望将不包含文本“=”的单元格设置为“文本”。
即使单元格格式设置为“常规”,也可以强制Excel将数字解释为string,方法是将单引号附加到数字的开头。
ActiveSheet.Cells(1, 1).Value = "'5.80" '...or... ActiveSheet.Cells(2, 1).Value = "'" & Format$(58 / 10, "#.00")