VBA - 如何检查String是否是有效的十六进制颜色代码?

时间:2016-11-18 15:37:35

标签: excel vba excel-vba exception error-handling

为了防止错误,我需要检查从自定义输入框中检索的String是否不是有效的十六进制颜色代码。到目前为止,我发现了其他语言的各种解决方案,但VBA没有。

使用以下代码,给出非十六进制值输入将导致运行时错误。这对我的项目至关重要,因为我正在处理受保护的工作表。

Public Function HexWindow(MyCell As String, Description As String, Caption As String)
    Dim myValue As Variant
    Dim priorValue As Variant
    priorValue = Range(MyCell).Value
    myValue = InputBox(Description, Caption, Range(MyCell).Value)
    Range(MyCell).Value = myValue
    If myValue = Empty Then
        Range(MyCell).Value = priorValue
    End If
    tHex = Mid(Range(MyCell).Text, 6, 2) & Mid(Range(MyCell).Text, 4, 2) & Mid(Range(MyCell).Text, 2, 2)
    Range(MyCell).Interior.Color = WorksheetFunction.Hex2Dec(tHex)
End Function

如何设置一个条件,该条件识别的值不是"#" &安培;在任何情况下,0-9和A-F都有6个字符?

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。最简单的方法是使用正则表达式:

'Requires reference to Microsoft VBScript Regular Expressions x.x
Private Function IsHex(inValue As String) As Boolean
    With New RegExp
        .Pattern = "^#[0-9A-F]{1,6}$"
        .IgnoreCase = True                'Optional depending on your requirement
        IsHex = .Test(inValue)
    End With
End Function

如果出于某种原因对您没有吸引力,您还可以利用VBA允许的十六进制字符串转换为数字:

Private Function IsHex(ByVal inValue As String) As Boolean
    If Left$(inValue, 1) <> "#" Then Exit Function
    inValue = Replace$(inValue, "#", "&H")
    On Error Resume Next
    Dim hexValue As Long
    hexValue = CLng(inValue)  'Type mismatch if not a number.
    If Err.Number = 0 And hexValue < 16 ^ 6 Then
        IsHex = True
    End If
End Function

答案 1 :(得分:0)

我会使用正则表达式。首先,您必须转到VBA编辑器中的Tools-->References(alt-f11),并确保选中此库

Microsoft VBScript Regular Expressions 5.5

然后您可以修改此示例代码以满足您的需求

Sub RegEx_Tester()
Set objRegExp_1 = CreateObject("vbscript.regexp")
objRegExp_1.Global = True
objRegExp_1.IgnoreCase = True
objRegExp_1.Pattern = "#[a-z0-9]{6}"
strToSearch = "#AAFFDD"
Set regExp_Matches = objRegExp_1.Execute(strToSearch)
If regExp_Matches.Count = 1 Then
    MsgBox ("This string is a valid hex code.")
End If
End Sub

此代码的主要功能是

objRegExp_1.Pattern = "#[a-z,A-Z,0-9]{6}"

它表示您将接受一个字符串,其中#后跟任意6个字符,这些字符是大写或小写字符串或数字0-9的组合。 strToSearch只是您正在测试的字符串,以查看它是否是有效的颜色十六进制字符串。我相信这对你有帮助。

我应该赞扬this site。如果您想要正则表达式的速成课程,可能需要查看它。一旦你学会了如何使用它们,它们就会很棒。