VBA:单元格字符串中最后一个中文的位置

1、这是一个自定义函数【经测试,答案不是很准】:直接上代码:

Function Byw(inputString As Range) As Integer
Application.Volatile
On Error Resume Next
Dim t, i As Integer
t = Len(inputString.Value)
For i = t - 1 To 0 Step -1
If Not System.Globalization.CharUnicodeInfo.GetUnicodeCategory(inputString(i)) = Globalization.UnicodeCategory.OtherLetter Then
lastNonChineseIndex = i
Exit For
End If
Next

' 如果没有找到非中文字符,lastNonChineseIndex 将保持为 0 或负数
If lastNonChineseIndex >= 0 Then
'Console.WriteLine ("最后一个非中文字符的位置是:" & lastNonChineseIndex)
Byw = lastNonChineseIndex
Else
'Console.WriteLine ("没有找到非中文字符。")
Byw = 0
End If
End Function

注意:在VBA中,获取字符串长度的函数是Len而不是Length。

比如:inputString.Length 是不管用的,换成Len(inputString)即可。

2、方法二【FindLastNonChineseChar】更合适:

Function FindLastNonChineseChar(str As String) As Integer
    Dim regEx As Object
    Dim matches As Object
    Dim lastIndex As Integer
    
    ' 创建正则表达式对象
    Set regEx = CreateObject("VBScript.RegExp")
    ' 匹配所有非中文字符
    regEx.Pattern = "[^\u4E00-\u9FA5]"
    regEx.Global = True
    ' 执行匹配
    Set matches = regEx.Execute(str)
    
    ' 如果没有匹配到,返回-1
    If matches.Count = 0 Then
        FindLastNonChineseChar = -1
    Else
        ' 获取最后一个匹配的位置
        lastIndex = matches(matches.Count - 1).FirstIndex
        ' 返回最后一个非中文字符的位置
        FindLastNonChineseChar = lastIndex
    End If
    
    ' 清理
    Set regEx = Nothing
    Set matches = Nothing
End Function