Search code examples
vbahttpcomboboxms-word

MS Word VBA, trying to populate a combobox with data from an http call


I'm using the following code to populate a combobox in Word 2003.

Private Sub UserForm_Initialize()
ComboBox1.List = Array("Red", "Green", "Yellow", "Blue")
End Sub

What I would like to do is get the data dynamically via an http call. This other function seems to work to get data via http

Dim MyRequest As Object

Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", _
"http://localhost:8500/test7.htm"

' Send Request.
MyRequest.Send

'And we get this response
MsgBox MyRequest.ResponseText

test7.htm just contains

"Red", "Green", "Yellow", "Blue"

I was hoping to combine the two but below doesn't work

Private Sub UserForm_Initialize()
Dim MyRequest As Object

Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", _
"http://localhost:8500/test7.htm"

' Send Request.
MyRequest.Send


ComboBox1.List = Array(MyRequest.ResponseText)
End Sub

Any help for a VBA noob appreciated


Solution

  • The response text should be a simple comma separated string, something like

    Red,Green,Yellow,Blue

    Thus you can use the following method for populating the ComboBox:

    Private Sub populateComboBox(ByRef combo As ComboBox, ByRef html As String)
        Dim arrayValues() As String, index As Integer
        arrayValues = Split(Trim(html), ",")
        For index = LBound(arrayValues) To UBound(arrayValues)
            combo.AddItem (arrayValues(index))
        Next
    End Sub
    

    For calling the method you can use the following sentence.

    Call populateComboBox(Combo1, MyRequest.ResponseText)