Skip to content

Instantly share code, notes, and snippets.

@Richienb
Last active August 24, 2024 14:34
Show Gist options
  • Save Richienb/51021a1c16995a07478dfa20a6db725c to your computer and use it in GitHub Desktop.
Save Richienb/51021a1c16995a07478dfa20a6db725c to your computer and use it in GitHub Desktop.
Download A File In Visual Basic Script (vbs)
Sub HTTPDownload( myURL, myPath )
Dim i, objFile, objFSO, objHTTP, strFile, strMsg
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set objFSO = CreateObject( "Scripting.FileSystemObject" )
If objFSO.FolderExists( myPath ) Then
strFile = objFSO.BuildPath( myPath, Mid( myURL, InStrRev( myURL, "/" ) + 1 ) )
ElseIf objFSO.FolderExists( Left( myPath, InStrRev( myPath, "\" ) - 1 ) ) Then
strFile = myPath
Else
WScript.Echo "ERROR: Target folder not found."
Exit Sub
End If
Set objFile = objFSO.OpenTextFile( strFile, ForWriting, True )
Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )
objHTTP.Open "GET", myURL, False
objHTTP.Send
For i = 1 To LenB( objHTTP.ResponseBody )
objFile.Write Chr( AscB( MidB( objHTTP.ResponseBody, i, 1 ) ) )
Next
objFile.Close( )
End Sub
HTTPDownload "DOWNLOADURL", "DOWNLOADDESTINATION"
@guffshop
Copy link

guffshop commented Jul 8, 2021

ik

Copy link

ghost commented Aug 16, 2021

good

@doddaa11
Copy link

1111

@amartineau70
Copy link

good

@lexicon454
Copy link

lexicon454 commented Feb 22, 2023

I applied this code in VBA. loop with "objFile.Write" works quite slowly. I managed to speed up the code.

Sub HTTPDownload(myURL, myPath, myName)
Dim i, objFile, objFSO, objHTTP, strFile, strMsg
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(myPath) Then
strFile = objFSO.BuildPath(myPath, myName)
ElseIf objFSO.FolderExists(Left(myPath, myName)) Then
strFile = myPath
Else
WScript.Echo "ERROR: Target folder not found."
Exit Sub
End If
Set objFile = objFSO.OpenTextFile(strFile, ForWriting, True)
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
objHTTP.Open "GET", myURL, False
objHTTP.Send

Dim start As Date
'start = Timer

Dim simbol_byte, simbol_text(), simbol$

simbol_byte = objHTTP.ResponseBody

ReDim simbol_text(LBound(simbol_byte) To UBound(simbol_byte))

For i = LBound(simbol_byte) To UBound(simbol_byte)
simbol_text(i) = Chr(simbol_byte(i))
If i Mod 100000 = 0 Then DoEvents
Next

simbol = ""
For i = LBound(simbol_text) To UBound(simbol_text)
simbol = simbol + simbol_text(i)
If i Mod 1000 = 0 Then DoEvents: objFile.Write simbol: simbol = "" ': Stop
Next
'MsgBox "Macro execution time " & Format((Timer - start) / 86400, "Long Time")
objFile.Close
End Sub

HTTPDownload Link, myPath, myName

@pastareal
Copy link

got expected ')' error when replacing myURL with download link
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment