3

. 我有一个 excel 电子表格,其中包含一些带有 unicode 控制字符的字符串,这些字符串在 Windows 7 中不可见。因此,我想编写一个宏来遍历列中的每个单元格,检查是否存在控制字符。如果找到控制字符,我想用字符名称和可以在字符串中找到的索引填充下一列中的相邻单元格。

这是我到目前为止所拥有的:

Sub control_chr()
'
' control_chr Macro
'

'
    Dim control_characters(Chr(28), Chr(29), Chr(30), Chr(31), Chr(32))
    Dim r As Range, cell As Range

    Set r = Range("F4:F1029")

    For Each cell In r
        For Each Character In control_characters

下一步是在单元格中搜索每个字符并用结果填充相邻的单元格。我的第一个想法是使用 SEARCH() 函数,因为它返回找到字符的位置的索引。这是我第一次使用visual basic,我不知道如何继续

4

2 回答 2

1

这是一些可以满足您要求的代码:

Sub ListControlChars()
Dim control_characters As Variant
Dim r As Range, cell As Range, ResultCell As Range
Dim CharPosition As Long
Dim i As Long

control_characters = Array(28, 29, 30, 31, 32)
Set r = ActiveSheet.Range("F4:F1029")

For Each cell In r
    Set ResultCell = cell.Offset(0, 1)
    ResultCell.ClearContents
    CharPosition = 0
    For i = LBound(control_characters) To UBound(control_characters)
    CharPosition = InStr(cell, Chr(control_characters(i)))
        If CharPosition > 0 Then
        ResultCell = ResultCell.Value & "Char " & control_characters(i) & ": Position " & CharPosition & " - "
        End If
    Next i
Next cell
End Sub

如果您想在 Excel 中执行此操作,可以这样设置:

在此处输入图像描述

B2中的公式为:

=IFERROR(SEARCH(CHAR(B$1),$A2),"")
于 2013-08-15T15:03:00.230 回答
0

我不记得我是否将其编码或在其他地方找到了它,但是当遇到将数据加载到某些数据库中遇到无法识别的特殊字符失败的问题时,这对我有用

Function IterateThruCells()    
Dim cell As Range    
   For Each cell In ActiveSheet.UsedRange.Cells
       If cell.Value <> "" Then
          If ContainsSpecialCharacters(cell.Value) = True Then
              Debug.Print cell.Address & ": " & cell.Value
          End If
       End If
   Next
End Function


               
Function ContainsSpecialCharacters(str As String) As Boolean
Dim I
For I = 1 To Len(str)
    ch = Mid(str, I, 1)
    Select Case ch
         Case "0" To "9", "A" To "Z", "a" To "z", " ", "(", ")", "/", "-", ".", ",", "_", "&", "'", "$", ">", "<", "–&quot;
         ContainsSpecialCharacters = False
            
    Case Else
         ContainsSpecialCharacters = True
         Exit For    
    End Select
           
Next
End Function
于 2022-01-14T22:44:59.740 回答