VBA选择性地将双字节转换为单个字符

时间:2017-02-07 07:09:59

标签: excel vba excel-vba encoding character-encoding

我已经编写了我的第一个VBA子程序,并且它的工作方式与它应该的方式相同,但我无法找出错误的部分。当存在一串双字节日语和拉丁语字符和空格时,它应该选择性地将双字节空格,字母,数字和标点符号转换为单字节。

In this picture, the top row represents the input and the bottom row the desired output of spaces, letters, numbers, and punctuation converted to single-byte while the Japanese characters remain intact.

However, this is what is happening when I run the sub. Clearly it's working, but also something is off with my concatenation.

代码如下所示,基于“捕获和转换”与有问题的全角字符对应的UTF-16代码范围。它只在本地化的机器上运行(即当语言/区域设置为日本时)但我不认为我的代码的问题与本地化的功能有关。对我所做错的任何帮助都会非常感激!

Public Sub Converter()
    Dim objRange As Range
        For Each objRange In ActiveSheet.UsedRange
        Call Alphanumeric(objRange)
    Next
End Sub

Private Sub Alphanumeric(ByRef objRange As Range)
    Dim strIn As String
    Dim strOut As String
    Dim strAlphanumeric As String
    Dim i As Integer

    If objRange.HasFormula Or _
        VarType(objRange.Value) <> vbString Then
        Exit Sub
    End If

    strIn = objRange.Value
    strOut = ""
    strAlphanumeric = ""

    For i = 1 To Len(strIn)
        If AscW(Mid(strIn, i, 2)) + 65536 >= 65280 And _
           AscW(Mid(strIn, i, 2)) + 65536 <= 65370 Then
           strAlphanumeric = strAlphanumeric & Mid(strIn, i, 1)
        Else
            If strAlphanumeric <> "" Then
                strOut = strOut & StrConv(strIn, vbNarrow)
                strAlphanumeric = ""
            End If
            strOut = strOut & Mid(strIn, i, 1)
        End If
    Next

    objRange.Value = strOut

End Sub

1 个答案:

答案 0 :(得分:0)

我怀疑这行

  

import re aggregate = {} conf = '$ip - $user [$date:$time $milis] "$request"' regex = ''.join( '(?P<' + g + '>.*?)' if g else re.escape(c) for g, c in re.findall(r'\$(\w+)|(.)', conf)) with open('example.log', 'r') as f: for line in f: m = re.match(regex, line.strip()) d = m.groupdict() if not aggregate.get(d['ip']): aggregate[d['ip']] = [] aggregate[d['ip']].append((d['date'], d['time'], d['milis'], d['request'])) with open('out.log', 'w') as out: for key in aggregate: out.write('"{0}", {1} times,\n'.format(key, len(aggregate[key]))) for item in aggregate[key]: out.write('"{0}","{1}","{2}","{3}"\n'.format(*item)) out.write('\n')

应该是我的眼睛

strOut = strOut & StrConv(strIn, vbNarrow)