无法用excel中的VBA替换Chr(160)

时间:2013-12-16 20:30:21

标签: vba special-characters

我一直在接收excel文件一段时间,这些文件通常在帐户之后受到特殊字符alt + 0160的困扰。我通常只是在excel手动替换它,但最近我变得懒惰,并希望使用我的VBA脚本替换它。此脚本用于将所需的列插入到我们的数据库中:

Sub insert()

    Dim sSql As String
    Dim db As New ADODB.Connection 'Go to Tools, References and turn on ActiveX Data Objects 2.8 Library
    db.Open "DSN=XXXX;uid=XXXX;pwd=XXXX" 'INSERT ORACLE NAME AND PASSWORD

    For i = 2 To 92 'Change Rows where it starts and ends

            strAccount = Replace(Trim(Range("a" & i).Text), Chr(160), "")

            If IsNumeric(strAccount) Then
                    While Len(strAccount) < 8
                            strAccount = "0" & strAccount
                    Wend
            Else
                    strAccount = UCase(strAccount)
            End If

    sSql = "insert into XXXXX ("
    sSql = sSql & "    BATCH_ID"
    sSql = sSql & "  , ACCOUNT "
    sSql = sSql & "  , ATTORNEY_ID"
    sSql = sSql & "  , ORG_ID"
    sSql = sSql & "  , TRANSACTION_DATE"
    sSql = sSql & "  , DATE_INSERTED"
    sSql = sSql & "  , TRANSACTION_CODE"
    sSql = sSql & "  , AMOUNT"
    sSql = sSql & "  , DESCRIPTION"
    sSql = sSql & "  , DEBTOR_SSN"

    sSql = sSql & ") VALUES ("
    sSql = sSql & "    (SELECT MAX(BATCH_ID) FROM XXXX)"
    sSql = sSql & "  , '" & strAccount & "'"
    sSql = sSql & "  , (SELECT ATTY_ID FROM XXXX WHERE BATCH_ID = (SELECT MAX(BATCH_ID) FROM XXXXX))"
    sSql = sSql & "  , (SELECT ORGANIZATION_ID FROM XXXX WHERE BATCH_ID = (SELECT MAX(BATCH_ID) FROM XXXXX))"
    sSql = sSql & "  , TO_DATE ('" & Trim(Range("B" & i).Text) & "', 'MM/DD/YYYY') "
    sSql = sSql & "  , SYSDATE"
    sSql = sSql & "  , '" & Trim(Range("D" & i).Text) & "'" 'CHANGE TO COLUMN TRANSACTION CODE IS IN
    sSql = sSql & "  , '" & Replace(Replace(Replace(Replace(Trim(Range("C" & i).Text), "$", ""), ",", ""), ")", ""), "(", "") & "'"
    sSql = sSql & "  , '" & Replace(Trim(Range("H" & i).Text), "'", "''") & "'"
    sSql = sSql & "  , '" & Replace(Replace(Trim(Range("F" & i).Text), " ", ""), "-", "") & "'"

    sSql = sSql & ")"


    db.Execute sSql

    DoEvents
    Debug.Print i

    Next i
End Sub

现在我做了一些研究,发现要用Chr(160)代替这些字符。我已经在我的Replace中使用了它,但它似乎没有做到这一点,帐户仍然上传了那些可怕的特殊字符。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

以下是我要解决的问题。我创建了一个函数来帮助处理这种情况,现在它可以正常工作。

Function CleanText(strText As String) As String
    If strText = "" Then
        CleanText = ""
    Else
        strText = Replace(strText, "'", "''")
        strText = Replace(strText, " ", "")
        strText = Replace(strText, vbTab, " ")
        strText = Replace(strText, vbCrLf, " ")
        strText = Replace(strText, Chr(160), "")
        CleanText = strText
    End If
End Function