Comment encoder une URL en VBA Excel ?

Comment encoder une chaîne pour une utilisation dans une URL en Excel VBA ?

VBA n’a pas de fonction native d’encodage URL. Voici une fonction personnalisée :

Function URLEncode(str As String) As String
    Dim i As Integer
    Dim c As String
    Dim result As String
    
    For i = 1 To Len(str)
        c = Mid(str, i, 1)
        If c Like "[A-Za-z0-9]" Or c = "-" Or c = "_" Or c = "." Or c = "~" Then
            result = result & c
        Else
            result = result & "%" & Right("0" & Hex(Asc(c)), 2)
        End If
    Next
    URLEncode = result
End Function

Ou utilisez WorksheetFunction.EncodeURL (disponible dans Excel 2013+) :

result = Application.WorksheetFunction.EncodeURL(str)