简体   繁体   English

使用没有日期/时间格式的 Excel VBA 检查时间

[英]Checking Time using Excel VBA without date/time format

I'm trying to ensure that the user of the tool only inserts valid time values.我试图确保该工具的用户只插入有效的时间值。 This input need to be numeric and not in datetime format.此输入必须是数字,而不是日期时间格式。 I understand that conditional formatting from the front-end would be a lot simpler, but a copy-paste action will overwrite the conditional formatting.我知道来自前端的条件格式会简单得多,但复制粘贴操作将覆盖条件格式。 So I've decided to write in a macro for it with the following logic : 1) Input has to be in number format '0000' 2) The first 2 digits have to be lesser than 23 AND 3) The last 2 digits have to be lesser than 59所以我决定用以下逻辑为它写一个宏:1) 输入必须是数字格式 '0000' 2) 前 2 位数字必须小于 23 和 3) 最后 2 位数字必须小于 59

This is the code I have so far but it's not giving me the intended output.这是我到目前为止的代码,但它没有给我预期的输出。 Where is the error or is there a more effective way of solving this?错误在哪里或者是否有更有效的方法来解决这个问题?

Worksheets("SheetA").Range("A2:A" & lastRow).NumberFormat = "0000"

For count = 2 To (lastRow + 1)
If IsEmpty(Worksheets("SheetA").Range("A" & count).Value) = True Then
    Worksheets("SheetA").Range("A" & count).Interior.Color = RGB(255, 255, 204)
Else
    If (Left(Worksheets("SheetA").Range("A" & count).Text, 2)) > 23 Or (Right(Worksheets("SheetA").Range("A" & count).Text, 2)) > 59 Then
        Worksheets("SheetA").Range("A" & count).Interior.Color = RGB(255, 0, 0)
    End If
End If
Next count 

In a normal module create a procedure to format your number as text and test it's within the required range:在普通模块中创建一个程序来将您的数字格式化为文本并测试它是否在所需范围内:

Public Sub TestNumber(Target As Range)

    Dim FormattedNumber As String

    'Return formatted "text" version of value.
    FormattedNumber = Format(Target, "0000")

    'Assume the value is correct and set the cell to "valid" colour.
    Target.Interior.Color = RGB(255, 255, 204)

    'Validate the value - check it's length, that it's a number
    'and falls with the specified ranges.
    If Len(FormattedNumber) = 4 And IsNumeric(Val(FormattedNumber)) Then
        If Val(Left(FormattedNumber, 2)) < 0 Or Val(Left(FormattedNumber, 2)) > 23 Or _
         Val(Right(FormattedNumber, 2)) < 0 Or Val(Right(FormattedNumber, 2)) > 59 Then
            Target.Interior.Color = RGB(255, 0, 0)
        Else
            'Remove if you don't want to reformat the number.
            Target.Value = Format(FormattedNumber, "00:00")
        End If
    Else
        Target.Interior.Color = RGB(255, 0, 0)
    End If

End Sub

On each sheet you want to check numbers in column 1 add this code:在要检查第 1 列中的数字的每张纸上,添加以下代码:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rCell As Range

    If Not Intersect(Target, Columns(1)) Is Nothing Then
        Application.EnableEvents = False
            For Each rCell In Target
                TestNumber rCell
            Next rCell
        Application.EnableEvents = True
    End If

End Sub

The Application.EnableEvents lines are only required if you reformat the entered number at the end of the TestNumber procedure.仅当您在TestNumber过程结束时重新格式化输入的数字时,才需要Application.EnableEvents行。 Not adding the command fires the Change event a second time with the reformatted number - which will return incorrect results, before firing again and eventually returning 00:00 .不添加命令会使用重新格式化的数字第二次触发Change事件 - 这将返回错误的结果,然后再次触发并最终返回00:00

Edit:编辑:
Have updated the Change event so it will work if more than one cell is changed (if a range of numbers are pasted in) and changed an AND to an OR in the TestNumber procedure (it was accepting 6000 previously).已更新Change事件,因此如果Change多个单元格(如果粘贴了一系列数字)并在TestNumber过程TestNumber AND更改为OR (之前接受6000 ),则该TestNumberTestNumber

Edit again:再次编辑:
If you want to check the number as entered remove the FormattedNumber variable and replace with Target and format the column as text so you don't lose the leading 0.如果您想检查输入的数字,请删除FormattedNumber变量并替换为Target并将列格式化为文本,这样您就不会丢失前导 0。

LEFT Function (Worksheet / VBA) LEFT 函数(工作表/VBA)

The Excel LEFT function can be used both as a worksheet function and a VBA function. Excel LEFT 函数既可以用作工作表函数,也可以用作 VBA 函数。 The LEFT function returns the specified number of characters in a text string, starting from the first or left-most character. LEFT 函数返回文本字符串中指定数量的字符,从第一个或最左边的字符开始。 Use this function to extract a sub-string from the left part of a text string.使用此函数从文本字符串的左侧部分提取子字符串。 Syntax: LEFT(text_string, char_numbers).语法:LEFT(text_string, char_numbers)。 It is necessary to mention the text_string argument which is the text string from which you want to extract the specified number of characters.有必要提及 text_string 参数,它是您要从中提取指定数量字符的文本字符串。 The char_numbers argument is optional (when using as a worksheet function), which specifies the number of characters to extract from the text string. char_numbers 参数是可选的(当用作工作表函数时),它指定要从文本字符串中提取的字符数。 The char_numbers value should be equal to or greater than zero; char_numbers 值应等于或大于零; if it is greater than the length of the text string, the LEFT function will return the text string in full;如果大于文本字符串的长度,LEFT 函数将完整返回文本字符串; if omitted, it will default to 1. While using as a VBA function, it is necessary to specify both the arguments, and if text_string contains Null, the function also returns Null.如果省略,则默认为1。作为VBA函数使用时,需要同时指定两个参数,如果text_string包含Null,函数也返回Null。

If you want obtain your goal i have an alternative for you: your input have to be a string after your control you convert the string in number if is a time else no conversation.如果你想实现你的目标,我有一个替代方案:你的输入必须是一个字符串,在你的控制之后你将字符串转换为数字,否则没有对话。

to convert string in number example:转换数字示例中的字符串:

Dim finalNumber As Integer
    If IsNumeric(myVar) Then
        finalNumber = CInt(myVar)
    Else
        finalNumber = 0
    End If

and limit input with this step https://www.extendoffice.com/documents/excel/952-excel-cell-character-limit.html并使用此步骤限制输入https://www.extendoffice.com/documents/excel/952-excel-cell-character-limit.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM