Excel中的Cell_Changing事件

在用户input提交到单元格之前 ,是否有相当于VBA Cell_Change Event或VSTO事件? 在单元格中input新值之前,我需要添加一些检查。

WorkSheet_Change事件触发时,Excel已经修改了用户input并将其转换为不同的值。 我需要获取用户input的原始input。

编辑

更具体地说,我想阻止Excel将3E9这样的值转换为科学记数法,这种值恰好是我的情况下的有效(非数字/非科学)input。

这些值可以由用户在整个工作表中的任何单元格中input,所以我不能预先应用文本格式,因为这会阻止Excel在有效的数字数据上执行正常的function。

所以我打算:

  • 以某种方式抓取input,然后进入单元格并进行转换。
  • 然后检查它是否符合我正在观察的确切模式,并在该特定单元格上实时应用文本格式。

您可以捕捉正在使用的科学记谱法,并将其反转为文本string

用RegExp更新来处理parsing

  • 将有效值重新格式化为初始文本(即120E399E13
  • 使用消息replace损坏的值,以便将它们(其中单元格已经格式化为文本,所以下一次12E14保持为文本12E14

表单事件代码

 Private Sub Worksheet_Change(ByVal Target As Range) Dim rng1 As Range Dim strTmp As String Dim objRegex As Object Set objRegex = CreateObject("vbscript.regexp") With objRegex .Pattern = "([1-9]+)(0+)" Application.EnableEvents = False For Each rng1 In Target.Cells If rng1.NumberFormat = "0.00E+00" Then rng1.NumberFormat = "@" strTmp = Len(.Replace(rng1.Value, "$2")) If .Test(rng1.Value) Then rng1.Value = "'" & .Replace(rng1.Value, "$1E") & strTmp Else rng1.Value = "Pls re-enter as text" End If End If Next End With Application.EnableEvents = True End Sub 

什么关于撤消function?

 Private Sub Worksheet_Change(ByVal Target As Range) Dim OldValue As String, NewValue as string If Intersect(Target, Range("B:B")) Is Nothing Then Exit Sub With Application .EnableEvents = False .Undo 'this is before OldValue = Target.Cells(1).Value .Redo 'this is after Newvalue = Target.Cells(1).value 'do some check to see if you need to reverse the change If oldvalue > newvalue then .undo Msgbox "Not valid" end if .EnableEvents = True End With End Sub 

我想知道是否可以使用数据validation来帮助解决这个问题。 假设您有像3E9和4E7这样的有效input,但没有像5E2或7E1那样的有效input。 那么让我们进一步假设你很less有有效的数字input10米以上。 如果这种情况属实,那么当用户input10米以上的数字时,就可以提醒用户。 如果这是合法的,他们会解除警告,继续前进。 如果他们打算input一个文字string,他们可以取消input,并按照您的指示前面加撇号。 你可以像这样创buildDV:

 Allow: Custom Formula: =OR(ISTEXT(A1),A1<10^7) Style: Warning Title: Scientific Notation Msg: If you enter a string like '9E99' Excel will convert to a number in scientific notation format. If you want the literal string, precede it with an apostrophe. 

它可能会问你很多具体情况。 也许还有一些其他的特点,你可以使用DV来避免。 就像如果有人不太可能input一个整数,你可以DV来检查。