office交流网--QQ交流群号

Access培训群:792054000         Excel免费交流群群:686050929          Outlook交流群:221378704    

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

自定义VB中的urlencode函数,将URL中特殊部分进行编码

2021-07-02 14:14:00
roadbeg (顾先强)
原创
17438

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 的请求部分,同时它还便于将变量传递给下一页

分享