• <strong id="yd969"><track id="yd969"></track></strong>

    <li id="yd969"></li>
  • <rp id="yd969"><object id="yd969"></object></rp>
  • office交流網--QQ交流群號

    Access培訓群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

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

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

    2021-07-02 14:14:00
    roadbeg (顧先強)
    原創
    15846

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

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

    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

    因為當字符串數據以url的形式傳遞給web服務器時,字符串中是不允許出現空格和特殊字符的

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

    分享