如何获得用户在excel中input到单元格中的确切文本

我应该开始说,我不知道VBA

我必须在Excel中input大量的时间值。 因为它真的减慢了我在input时input冒号的速度,所以我想我会写一个macros让我input一个像“18.10”这样的string并将其转换为“18:10”。 (然后我可以使用数字键盘并快速input时间)。

我已经拼凑在一起的function来转换任何给定的(分隔)string到一个时间 – 这很容易。 但是现在我遇到了事件处理程序的麻烦,因为我无法得到我input的确切文本 ,因为Excel似乎将其视为数字并修剪尾部0。

例如,18.10被转换为18.1 – 被转换为18:01(而不是18:10,因为我想要)。

这是我的更改处理代码(从interweb复制)

Private Sub Worksheet_Change(ByVal Target As Excel.Range) Dim TimeStr As String ' This code copied from Chip Pearson 'http://www.cpearson.com/excel/DateTimeEntry.htm If Application.Intersect(Target, Range("C6:F1000")) Is Nothing Then Exit Sub End If If Target.Cells.Count > 1 Then Exit Sub End If If Target.Value = "" Then Exit Sub End If Application.EnableEvents = False With Target TimeStr = .Text ' What should I use here???? If .HasFormula = False Then .Value = ConvertToTime(TimeStr) End If End With Application.EnableEvents = True Exit Sub 

EndMacro:MsgBox“您没有input有效的时间”Application.EnableEvents = True End Sub

正如你所看到的,我现在正在使用Text – 我已经在debugging器中查看了Target上的所有属性,并且找不到任何看起来像是原始input文本的东西。 有没有办法获得价值?

任何帮助不胜感激。


谢谢Issun和Craig。 Issun是正确的 – 我使它变得过于复杂(转换到时间)。 这是我想出来的,工作得很好。

 ' This requires the format of the cells to ce "0.00" to prevent trailing 0s being trimmed Private Sub Worksheet_Change(ByVal Target As Excel.Range) On Error GoTo ErrHandler: Dim TimeStr As String Dim TimeVal ' I am only entering times in this range If Application.Intersect(Target, Range("C6:F1000")) Is Nothing Then Exit Sub End If If Target.Cells.Count > 1 Then Exit Sub End If If Target.Value = "" Then Exit Sub End If TimeStr = Replace(Target.Text, ".", ":") TimeVal = TimeValue(TimeStr) Application.EnableEvents = False Target.Value = TimeVal Target.NumberFormat = "h:mm" Application.EnableEvents = True Exit Sub ErrHandler: Exit Sub End Sub 

 Sub SetTimeFormat() Selection.NumberFormat = "h:mm" End Sub Sub SetNumFormat() Selection.NumberFormat = "0.00" End Sub 

正如在评论中提到的,我发现改变单元格格式为“0.00”效果很好。 时间input为“18.1”得到转换为“18:10”(而不是18:01),但实际上这是确定的我。

最后2个macros我分配给几个热键,所以如果我犯了一个错误,我可以快速将单元格的格式转换回数字并再次结束值。

如果将单元格的格式更改为文本(格式化单元格 – >文本),这将保留18.10,并允许您更轻松地parsing该值。

编辑:当你运行你的macros添加一行类似于:

 Selection.NumberFormat = "h:mm AM/PM" 

这应该然后重新格式化单元格的“时间”格式。

如果您只想将18.10更改为18:10,则单击工作表的左上angular以select所有单元格,并将格式更改为文本。 然后input并search并replace为“。”。 和“:”当你完成。

如果你愿意,这里有一个有趣的方式来自动格式化你input的内容。 在VBA编辑器中双击Sheet1或任何工作表,然后input下面的代码:

 Private Sub Worksheet_Change(ByVal Target As Range) If InStr(Target.Value, ".") <> 0 Then Application.EnableEvents = False Target.Value = Replace(Target.Value, ".", ":") Target.NumberFormat = "h:mm AM/PM" Application.EnableEvents = True End If End Sub 

这是做什么是首先检查是否有一个“。” 在刚刚更改或键入的单元格中。如果存在,则会closures事件(因此,要执行的更改不会触发另一个更改事件),则会replace“。”。 与“:”。 然后将其转换为时间格式。

这是一个发生的例子。 一个注意:对于xx:30,您需要input一个额外的“。” 所以Excel不会感到困惑。

1.15将成为1:15 AM

13.15将成为1:15 PM

16:30。 将成为下午4:30