首页 > 解决方案 > 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

标签: excelvba

解决方案


=此代码在 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 = "@"

推荐阅读