office交流網(wǎng)--QQ交流群號

Access培訓(xùn)群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

自定義VB中的urlencode函數(shù),將URL中特殊部分進行編碼

2021-07-02 14:14:00
roadbeg (顧先強)
原創(chuàng)
17094

URL編碼(URL encoding),也稱作百分號編碼(Percent-encoding), 是特定上下文的統(tǒng)一資源定位符 (URL)的編碼機制

在VBA中,沒有完整有效的類似 vb中的 urlencode 函數(shù),下面是自定義的 urlencode 函數(shù)

Public Function UrlEncode(Value As String) As String
    Value = Replace(Value, "%", "%25")
    Value = Replace(Value, "+", "%2B") '
    Value = Replace(Value, "@", "%40") '%40
    Value = Replace(Value, "=", "%3D")
    Value = Replace(Value, "?", "%3F")
    Value = Replace(Value, "&", "%26")
    Value = Replace(Value, ",", "%2C")
    Value = Replace(Value, ";", "%3B")
    Value = Replace(Value, "/", "%2F")
    Value = Replace(Value, """", "%22")
    Value = Replace(Value, "'", "%27") '
    Value = Replace(Value, "", "%5C") '
    Value = Replace(Value, ":", "%3A") '
    Value = Replace(Value, " ", "%20") '
    '
    Value = UrlEncode_ToUtf8(Value)
    
    UrlEncode = Value
End Function

'取得UTF-8
Private Function UrlEncode_ToUtf8(InputValue As String) As String
    Dim strWChar As String, strUChar As String, strRe As String
    Dim lngI As Long, lngLen As Long
    Dim nAsc As Integer
    If InputValue = "" Then
        UrlEncode_ToUtf8 = InputValue
    Else
        lngLen = Len(InputValue)
        For lngI = 1 To lngLen
            strWChar = mID$(InputValue, lngI, 1)
            nAsc = AscW(strWChar)
            If nAsc < 0 Then nAsc = nAsc + 65536
            
            If (nAsc And &HFF80) = 0 Then
                strRe = strRe & strWChar
            Else
                If (nAsc And &HF000) = 0 Then
                    strUChar = "%" & Hex$(((nAsc \ 2 ^ 6)) Or &HC0) & Hex$(nAsc And &H3F Or &H80)
                    strRe = strRe & strUChar
                Else
                    strUChar = "%" & Hex$((nAsc \ 2 ^ 12) Or &HE0) & "%" & _
                    Hex((nAsc \ 2 ^ 6) And &H3F Or &H80) & "%" & _
                    Hex(nAsc And &H3F Or &H80)
                    strRe = strRe & strUChar
                End If
            End If
        Next
        UrlEncode_ToUtf8 = strRe
    End If
    
End Function

因為當(dāng)字符串?dāng)?shù)據(jù)以url的形式傳遞給web服務(wù)器時,字符串中是不允許出現(xiàn)空格和特殊字符的

經(jīng)過裝換,便于將字符串用于 URL 的請求部分,同時它還便于將變量傳遞給下一頁

分享
文章分類
聯(lián)系我們
聯(lián)系人: 王先生
Email: 18449932@qq.com
QQ: 18449932
微博: officecn01
移動訪問