How to create Organisational Units via VBA (Excel)?

Thanks Eric for the assistance.

I ended up figuring it out by investigating the format that the API takes when doing it from the web app. For anyone looking for this (and similarly for other metadata types such as Data Elements) my import script looks like this.

strURL and strCSVFilePath are overwritten here to show working - additionally pushing the correct classkey as referenced from here: https://docs.dhis2.org/master/en/developer/html/webapi_csv_metadata_import.html

Private Function dhis2APIpostCSV(strURL As String, strUsr As String, strPwd As String, strCSVFilePath As String, ClassKey As String) As String
Dim Data As String

strURL = “https:///api/metadata.json?importMode=COMMIT&dryRun=undefined&identifier=UID&importReportMode=ERRORS&preheatMode=REFERENCE&importStrategy=CREATE_AND_UPDATE&atomicMode=ALL&mergeMode=MERGE&flushMode=AUTO&skipSharing=false&skipValidation=false&async=true&inclusionStrategy=NON_NULL&classKey=” & ClassKey & “&format=json”

'CSV File creation based on the structure - still need to write this creation with the VBNewLines

strCSVFilePath = “Name,UID,shortName” & vbNewLine & “SAMPLE 1,AoCzcvlpyuI,SAMPLE 1”

Dim MyRequest As Object
On Error GoTo dhis2APIpostErr ’

Application.Cursor = xlWait
Set MyRequest = CreateObject(“WinHttp.WinHttpRequest.5.1”)
MyRequest.Open “POST”, strURL, False
MyRequest.setRequestHeader “Content-Type”, “application/csv”
MyRequest.setRequestHeader “Authorization”, "Basic " & Encode64(strUsr & “:” & strPwd)
MyRequest.send strCSVFilePath
dhis2APIpostCSV = MyRequest.ResponseText
Application.Cursor = xlDefault
Exit Function

dhis2APIpostErr:
dhis2APIpostCSV = "API call failed. " & Err.Number & " - " & Err.Description
Application.Cursor = xlDefault

End Function

1 Like