'VBA Error on Stream.SaveToFile

I'm attempting to modify a VBA script from another post (26486871).

The script will download a Zip file, extract a text file and import the data to Excel.

I don't know VBA so I'll tackle each of the functions one at-a-time.

  1. Create a temp directory with a randomized name..........................Complete
  2. Download a Zip file from a public server................................Error
  3. Extract the text file (20MB, tab-delimited).............................Not Yet
  4. Import the data into the open worksheet (overwrite the existing data)...Not Yet

I'm receiving a Run-time Error with the Stream.SaveToFile: "Arguments are of the wrong type, are out of acceptable range or are in conflict."

I've tried options 1, 2 and adSaveCreateNotExists. However, the Zip file won't save to the temp folder.

I appreciate any help.

'Main Procedure
Sub DownloadExtractAndImport()

Dim url As String
Dim targetFolder As String, targetFileZip As String, targetFileTXT As String

Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
Dim newSheet As Worksheet

url = "http://www.example.com/data.zip"
targetFolder = Environ("TEMP") & "\" & RandomString(6) & "\"
MkDir targetFolder
targetFileZip = targetFolder & "data.zip"
targetFileTXT = targetFolder & "data.txt"

'1 download file
DownloadFile url, targetFileZip

End Sub

Private Sub DownloadFile(myURL As String, target As String)

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Msxml2.ServerXMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.send

myURL = WinHttpReq.responseBody
If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile targetFile, 1  ' 1 = no overwrite, 2 = overwrite
    oStream.Close
End If

End Sub

Private Function RandomString(cb As Integer) As String

Randomize
Dim rgch As String
rgch = "abcdefghijklmnopqrstuvwxyz"
rgch = rgch & UCase(rgch) & "0123456789"

Dim i As Long
For i = 1 To cb
    RandomString = RandomString & Mid$(rgch, Int(Rnd() * Len(rgch) + 1), 1)
Next

End Function


Solution 1:[1]

It is just a typo: it must be target, not targetFile, as targetFile is not specified. Please use Option Explicit to prevent errors like this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Graham