This script was previously reviewed here: Send HTTP request for each row in Excel table (Part 1)
I've made the changes that were suggested in the Code Review answers as well as added a few of my own.
The code is quite a bit different now. Are there any more improvements that should be made?
Description:
- A custom function concatenates columns with parameters into the
Concatenated Variables
column.- Loops through each row in the table where
Load? = y
- Sends an HTTP request to an external system using the value in the
URL
column.- Returns a message (created, updated, or problem/error) and stores it in the
Message
column.
New code:
Option Explicit
Public Const tblName = "tblData"
Public Const colNameLoad = "Load?"
Public Const colNameMessage = "Message"
Public Const colNameURL = "URL"
Public Const colNameTimestamp = "Message Timestamp"
Function CodeName() As Worksheet
Set CodeName = DataSheet
End Function
Public Sub LoadRecords()
Application.CalculateFull
Dim message As String, response As String
Dim n As Long
'Keep an eye on unecessary calls to the ConcatVars function.
With CodeName.ListObjects(tblName)
.ListColumns(colNameMessage).Range.Interior.Color = rgbWhite
.ListColumns(colNameMessage).Range.Font.Color = rgbLightGrey
For n = 1 To .ListRows.Count
If UCase(.ListColumns(colNameLoad).DataBodyRange(n).Value) = "Y" Then
response = GetHTTP(.ListColumns(colNameURL).DataBodyRange(n).Value)
.ListColumns(colNameMessage).DataBodyRange(n) = response
.ListColumns(colNameMessage).DataBodyRange(n).Font.Color = rgbBlack
.ListColumns(colNameTimestamp).DataBodyRange(n) = Now()
With .ListColumns(colNameMessage).DataBodyRange(n)
message = Left(response, 7)
.Interior.Color = Switch(message = "Created", rgbLightGreen, message = "Updated", rgbSkyBlue, message = "Problem", rgbYellow, True, rgbOrangeRed)
End With
End If
Next
End With
End Sub
Public Function GetHTTP(ByVal url As String) As String
On Error GoTo ConnectionError:
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", url, False: .Send
GetHTTP = VBA.StrConv(.responseBody, vbUnicode)
End With
On Error GoTo 0
Exit Function
ConnectionError:
GetHTTP = "Problem with URL or server: " & Err.Number & " " & Err.Description
End Function
Function ConcatVars(RowNum As Integer) As String
Dim Column As ListColumn
Dim s As String
For Each Column In CodeName.ListObjects(tblName).ListColumns
If Column.Name Like "f_*" Then
s = s & IIf(Len(s) > 0, "&", "") _
& Mid(Column.Name & "=" & Column.Range.Cells(RowNum).Value, 3)
End If
Next
ConcatVars = s
End Function
I have a follow-up question here: Create or update record via HTTP request (Python/Jython).