vba Excel:如何将代码添加到单元格的失去焦点事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17207477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:46:51  来源:igfitidea点击:

Excel: How can I add code to a lost focus Event of a cell?

excel-vbavbaexcel

提问by Lenin

Is there a way to add code to the LostFocusevent of the cells in a sheet?

有没有办法将代码添加到工作表中单元格的LostFocus事件?

I want to add code to keep the first 50 characters of the cell that loses the focus:

我想添加代码以保留失去焦点的单元格的前 50 个字符:

If Len(ActiveCell.FormulaR1C1) > 50 Then
    ActiveCell.FormulaR1C1 = Left$(ActiveCell.FormulaR1C1, 47) + "..."
End If

回答by chris neilsen

There is no Lost Focusevent. Try this instead

没有失去焦点事件。试试这个

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Static OldRange As Range
    If Not OldRange Is Nothing Then
        If Not OldRange.HasFormula Then
            If Len(OldRange.Value) > 50 Then
                OldRange.Value = Left$(OldRange.Value, 47) + "..."
            End If
        End If
    End If
    Set OldRange = Target.Cells(1, 1)
End Sub

Note, I don't think you want to use FormulaR1C1because if you happen to have a formula where the Formula it self is longer than 50 chars, the code as posted would put an invalid formula into the cell. What I've posted ignores formulas, even if they return a result longer than 50 chars. If required this could be changed to convert the formula to its truncated result.

请注意,我认为您不想使用,FormulaR1C1因为如果您碰巧有一个公式,其自身长度超过 50 个字符,则发布的代码会将无效公式放入单元格中。我发布的内容忽略了公式,即使它们返回的结果超过 50 个字符。如果需要,可以更改它以将公式转换为其截断的结果。

Note also that this handles multi-cell selections poorly. You would have to consider your use case carefully in this regard.

另请注意,这无法很好地处理多单元格选择。在这方面,您必须仔细考虑您的用例。

回答by exussum

Private Sub Workbook_SheetSelectionChange(ByVal Sheet As Object, ByVal Target As Range)

End Sub

using that you can see whta you changed too, If you keep a variable with what it changed from you should be able to track it easily

使用它你可以看到你也改变了什么,如果你保留一个变量,它改变了你应该能够轻松跟踪它