子string不被识别为值

我试图创build的macros将扫描一系列单元格,提取唯一的特殊字符,并将它们放入不断增长的唯一特殊字符列表(即没有特殊字符列出两次)。

我使用了不同来源的代码,但是我遇到的最后一个问题是,当我尝试将列中的下一个空单元格设置为特殊字符时,Excel会生成一个1004:应用程序定义的或面向对象的错误。

Sub Main() Dim sCharOk As String Dim s As String Dim r As Range, rc As Range Dim j As Long sCharOk = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,-() ~!@#%^&*()_+?'." Set r = Range("A1:A10") For Each rc In r s = rc.Value For j = 1 To Len(s) If InStr(sCharOk, Mid(s, j, 1)) = 0 And Application.WorksheetFunction.CountIf(Range("B1:B100"), Mid(s, j, 1)) = 0 Then rc.Interior.Color = vbYellow Mid(s, j, 1) = Range("B1").End(xlDown).Offset(1, 0) Exit For End If Next j Next rc End Sub 

有什么办法可以告诉Excel把这个认为是一个合法的对象,或者不是这个问题?

 Sub Main() Dim sCharOk As String Dim s As String Dim r As Range, rc As Range Dim j As Long sCharOk = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,-() ~!@#%^&*()_+?'." Set r = Range("A1:A10") For Each rc In r s = rc.Value For j = 1 To Len(s) If InStr(sCharOk, Mid(s, j, 1)) = 0 And _ Application.CountIf(Range("B1:B100"), Mid(s, j, 1)) = 0 Then rc.Interior.Color = vbYellow Cells(rows.count,2).End(xlUp).offset(1,0).value = Mid(s, j, 1) Exit For '<<< remove if you want to capture all special chars End If Next j Next rc End Sub 

你可以使用Dictionary对象来处理唯一的值

这是一个带有后期绑定Dictionary实例的例子

 Option Explicit Sub Main() Dim sCharOk As String Dim s As String Dim r As Range, rc As Range Dim j As Long sCharOk = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,-() ~!@#%^&*()_+?'." Set r = Range("A1:A10") With CreateObject("Scripting.Dictionary") '<--| instantiate a 'Dictionary' object For Each rc In r s = rc.Value For j = 1 To Len(s) If InStr(sCharOk, Mid(s, j, 1)) = 0 Then .Item(Mid(s, j, 1)) = .Item(Mid(s, j, 1)) + 1 '<--| stores invalid character in dictionary keys, if not already there rc.Interior.Color = vbYellow Exit For End If Next j Next rc Cells(Rows.count, 2).End(xlUp).Offset(1, 0).Resize(.count).Value = Application.Transpose(.Keys) '<--| write down dictionary keys (ie unique invalid characters) End With End Sub