excel - Excel等号作为单元格中的第一个字符
问题描述
我正在尝试将等号“=”作为单元格中的第一个字符,以让单元格进行计算。例如,A 列表示(如果存在)像 '=12*12' 这样的公式,因此您可以在 B 列中看到结果背后的内容。通过这种行为,我试图让 Excel 像受 Speedcruch 和 Speq 等程序启发的计算器一样工作。不幸的是,当我尝试一些代码时,Excel 正在做一些奇怪的事情,看起来活动单元格正在跳转到一种随机单元格。这就是我所得到的:这里出了什么问题?
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("B1:B1000")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
If Left(Range(Target.Address), 1) = "=" Then
' Do nothing
Else
Range(Target.Address) = "=" & Range(Target.Address)
Range(Target.Address).Select
End If
End If
End Sub
更改代码:
Private Sub Worksheet_Change(ByVal Target As Range)
' Do nothing if more than one cell is changed or content deleted
'If Target.Cells.Count > 1 Or IsEmpty(Target) Then Exit Sub
If Not Intersect(Target, Range("B1:B1000")) Is Nothing Then
' Change the range required
' Ensure target is a number before doing anything
'If IsNumeric(Target) Then
' Stop any runtime errors
On Error Resume Next
' Turn off events so a change doesn’t start an endless loop
Application.EnableEvents = False
Dim Value
Value = Chr(61) & Range(Target.Address).Value
'MsgBox "Value: " & Value 'Range(Target.Address).Value
If Left(Range(Target.Address).Value, 1) <> Chr(61) Then
MsgBox "Value: " & Value
Range(Target.Address).Formula = Value
End If
' Turn events on
Application.EnableEvents = True
' Allow run time errors again
On Error GoTo 0
'End If
End If
End Sub
解决方案
=
此代码在 B 列中的每个条目前面放置一个等号 (' ')。
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Not Intersect(Target, Range("B1:B1000")) Is Nothing _
And Left(Target.Value, 1) <> Chr(61) Then
Target.NumberFormat = "@"
Target = Chr(61) & Target.Value
End If
Application.EnableEvents = True
End Sub
要让 Excel 不将等号视为公式指示符,您需要将NumberFormat
属性设置为“文本”,这在此行中完成:
Target.NumberFormat = "@"
推荐阅读
- python - TensorFlow Github 存储库中定义的 Softmax 函数
- javascript - 线程“main”中的异常 java.lang.NullPointerException 如何检查来自另一个类(Java 对象和类)的客户
- c# - C# 在 OrderBy 中使用 GroupBy
- hyperledger-fabric - 使用超级账本结构在同一通道上部署多个链码
- javascript - 如何在没有模板引擎的情况下快速呈现动态 HTML 文件
- jquery - 如何在 asp.net 中对数据进行分组?
- spring - Spring Batch 多线程与 Partitioner
- html - 如何进行 HTML/CSS 定位
- linux - FFmpeg 在给定时间将音频剪辑混合到一个主音频文件中
- scikit-learn - KNeighborsRegressor 和 KNNImputer 有什么区别