Skip to main content

How to URL Encode a String in Excel VBA?

Is there a built-in way to URL encode strings in Excel VBA, or do I need to manually code this functionality?

Before Excel 2013

htmlfile ActiveX

Function EncodeUriComponent(strText)
    Static objHtmlfile As Object
    If objHtmlfile Is Nothing Then
        Set objHtmlfile = CreateObject("htmlfile")
        objHtmlfile.parentWindow.execScript "function encode(s) {return encodeURIComponent(s)}", "jscript"
    End If
    EncodeUriComponent = objHtmlfile.parentWindow.encode(strText)
End Function

Declaring htmlfile DOM document object as static variable gives the only small delay when called first time due to init, and makes this function very fast for numerous calls.

JScript

Not available for 64-bit Office editions.

Function EncodeURL(str As String)
    Dim ScriptEngine As Object
    Dim encoded As String
    Set ScriptEngine = CreateObject("scriptcontrol")
    ScriptEngine.Language = "JScript"
    encoded = ScriptEngine.Run("encodeURIComponent", str)
    EncodeURL = encoded
End Function

Excel 2013 and later

Since Excel 2013 there is now a built-in way of encoding URLs using the worksheet function ENCODEURL.

To use it in your VBA code you just need to call:

sEncodedUrl = WorksheetFunction.EncodeUrl(InputString)

Leave a comment

Your email address will not be published. Required fields are marked *

Format your code: <pre><code class="language-vba">place your code here</code></pre>