VBA:单元格中第一个非中文字符的位置

Function FindFirstNonChineseChar(s As String) As Integer
    Dim i As Integer
    For i = 1 To Len(s)
        If AscW(Mid(s, i, 1)) > 255 Then ' 假设非中文字符的ASCII码大于255
            FindFirstNonChineseChar = i
            Exit Function
        End If
    Next i
    FindFirstNonChineseChar = 0 ' 如果没有找到非中文字符,则返回0
End Function

第二:

Sub TestFindFirstNonChineseChar()
    Dim testStr As String
    testStr = "你好,世界!Hello, World!"
    Dim position As Integer
    position = FindFirstNonChineseChar(testStr)
    If position > 0 Then
        Debug.Print "第一个非中文字符出现在位置:" & position
    Else
        Debug.Print "字符串中没有非中文字符"
    End If
End Sub

三:管用

Function FindFirstNonChineseCharIndex(str As String) As Integer
    Dim regEx As Object
    Dim matches As Object
    Dim result As Integer
    result = -1 ' 初始化结果为-1,表示没有找到非中文字符
    
    ' 创建正则表达式对象
    Set regEx = CreateObject("VBScript.RegExp")
    ' 匹配非中文字符
    regEx.Pattern = "[^\u4e00-\u9fa5]"
    regEx.Global = True
    
    ' 执行匹配
    Set matches = regEx.Execute(str)
    
    ' 检查是否有匹配
    If matches.Count > 0 Then
        ' 获取第一个匹配的位置
        result = matches(0).FirstIndex + 1 ' +1 因为FirstIndex是基于0的
    End If
    
    FindFirstNonChineseCharIndex = result
End Function