如何在Excel中分离/过滤英文文本和中文

时间:2016-09-28 00:42:27

标签: excel vba excel-vba function filter

我正在开发一个包含多个Excel文件的项目,其中包含包含英文,中文或英文和中文的单元格。

我需要保留完全使用中文的行并将它们放在第一位。然后,我需要包含中文和英文的行。只有那些只有英文的人。

我遇到了以下3个功能,可以帮助我相应地标记内容,但它们似乎没有按预期工作,我无法弄清楚原因。

Function ExtractChn(txt As String)
Dim i As Integer
Dim ChnTxt As String
For i = 1 To Len(txt)
    If Asc(Mid(txt, i, 1)) < 0 Then
        ChnTxt = ChnTxt & Mid(txt, i, 1)
    End If
Next i
ExtractChn = ChnTxt
End Function

Function ExtractEng(txt As String)
Dim i As Integer
Dim EngTxt As String
For i = 1 To Len(txt)
    If Asc(Mid(txt, i, 1)) >= 0 Then
        EngTxt = EngTxt & Mid(txt, i, 1)
    End If
Next i
ExtractEng = EngTxt
End Function

Function CheckTxt(txt)
Dim i As Integer
Dim Eng As Integer
Dim Chn As Integer
Chn = 0
Eng = 0
For i = 1 To Len(txt)
    If Asc(Mid(txt, i, 1)) > 0 Then
        Eng = 1
    Else:
        Chn = 1
    End If
Next i
If Chn = 1 And Eng = 1 Then   'Contains Both Eng & Chn
    CheckTxt = "BOTH"
Else:
    If Chn = 1 And Eng = 0 Then    'Chn
        CheckTxt = "CHN"
    Else:
        If Chn = 0 And Eng = 1 Then   'Eng
            CheckTxt = "ENG"
        End If
    End If
End If
End Function

创建它们的人甚至提供了一个文件,演示了这些功能的工作原理。我将链接附加到文件,其安排如下:

Text|English part of it|Chinese part of it|ExtractEng|ExtractChn|CheckTxt

根据作者的意图,CheckTxt结果应显示CHENGBOTH。但是,它始终只显示ENG,我无法理解原因。

任何想法如何使它工作?除非有更简单的方法来提前过滤&#39; Excel中的内容?任何帮助将不胜感激。

Test Excel file from the developer

2 个答案:

答案 0 :(得分:1)

这听起来像是正则表达式的工作!!

enter image description here

Function getCharSet(Target As Range) As String
    Const ChinesePattern = "[\u4E00-\u9FFF\u6300-\u77FF\u7800-\u8CFF\u8D00-\u9FFF]+"
    Const EnglishPattern = "[A-Za-z]"
    Dim results As String
    Dim Data, v
    Dim Regex1 As Object
    Set Regex1 = CreateObject("VBScript.RegExp")
    Regex1.Global = True

    If Target.Count = 1 Then
        Data = Array(Target.Value2)
    Else
        Data = Target.Value2
    End If

    For Each v In Data

        If Not InStr(results, "CHN") Then
            Regex1.Pattern = ChinesePattern
            If Regex1.Test(v) Then
                If Len(results) Then
                    getCharSet = "CHN" & " - " & results
                    Exit Function
                Else
                    results = "CHN"
                End If
            End If
        End If

        If Not InStr(results, "ENG") Then
            Regex1.Pattern = EnglishPattern
            If Regex1.Test(v) Then
                If Len(results) Then
                    getCharSet = results & " - ENG"
                    Exit Function
                Else
                    results = "ENG"
                End If
            End If
        End If
    Next
    getCharSet = results

End Function

答案 1 :(得分:1)

基本方法:

func mapView(_ mapView: GMSMapView, didTap overlay: GMSOverlay) {
        //Write your code here
    }