Excel VBA的对象必需错误

时间:2016-09-12 15:21:32

标签: excel-vba vba excel

我已经使用了How to remove all non alphanumeric characters from a string except period and space in excel?,但一直在

  

需要对象

你可以看到我尝试过各种Err或If语句的文本,但遗憾的是这些语句没有修复。

Sub CleanAll()

Set wb = Workbooks("test.xlsm")
Dim rng As Range
' Dim i As Integer
' i = 1

For Each rng In wb.Sheets("Portal_Aligned").Range("A1:AX9999").Cells 'adjust sheetname and range accordingly
    rng.Value = CleanCode(rng.Value) & ""
    '   i = i + 1
Next

End Sub

Function CleanCode(strSource As String) As String

'On Error GoTo Err1
'http://www.asciitable.com/

Dim i As Integer
Dim strResult As String

' If strSource <> "" Then
For i = 1 To Len(strSource)
    Select Case Asc(Mid(strSource, i, 1))

        Case 32 To 33, 35 To 131, 133 To 135, 145 To 146, 150 To 152, 155, 162 To 166, 183, 188 To 190, 247
            strResult = strResult & Mid(strSource, i, 1)
    End Select
Next

'AlphaNumericOnly = strResult
'rng.Value = AlphaNumericOnly(rng.Value)
'  End If
Err1:

End Function

1 个答案:

答案 0 :(得分:1)

下面的代码(测试)将会运行,请记住,您允许的所有Case字符都有限制(例如双引号" })。

在您提供的参考链接中,PO会限制更多内容(例如:;=>等。

Sub CleanAll()

Set wb = Workbooks("test.xlsm")
Dim rng             As Range

For Each rng In wb.Sheets("Portal_Aligned").Range("A1:AX9999") 'adjust Sheet Name and range accordingly
    ' handle cells with emprty strings here
    If rng.Value <> "" Then
        rng.Value = CleanCode(rng.Value) & ""
    End If
Next

End Sub

Function CleanCode(strSource As String) As String

Dim i               As Integer
Dim strResult       As String

For i = 1 To Len(strSource)

    Select Case Asc(Mid(strSource, i, 1))

        Case 32 To 33, 35 To 131, 133 To 135, 145 To 146, 150 To 152, 155, 162 To 166, 183, 188 To 190, 247
            strResult = strResult & Mid(strSource, i, 1)

    End Select
Next

CleanCode = strResult

End Function
相关问题