Quick test professional

QTP Tips QTP codes QTP Faqs and more

How to Download a file using VbScript

Following is the code to download a file using Vbscript, without using QTP

This code uses the HTMLDom and URLDownloadToFile method from urlmon API.

Since VBScript does support calling Native API methods directly, here I am using  Excel macro to declare a function for the urlmon API and running the macro by Excel API from VBscript

Step1: Create a new excel and open the visual basic editor, Insert Module and paste the following code the Module, save the excel file

Private Declare Function URLDownloadToFile Lib “urlmon” Alias _
                                           “URLDownloadToFileA” ( _
                                           ByVal pCaller As Long, ByVal szURL As String, _
                                           ByVal szFileName As String, _
                                           ByVal dwReserved As Long, _
                                           ByVal lpfnCB As Long) As Long
Sub FileSave(strUrl, Des)
    r = URLDownloadToFile(0, strUrl, Des, 0, a)
   
End Sub

Step2: Create a VBS  and copy the below code and change the file paths

Set ie = CreateObject(“InternetExplorer.Application”)
ie.navigate “www.google.com
ie.Visible = True
WScript.Sleep 3000
ie.document.all.q.Value = “Testing + doc”
ie.document.all.btnG.Click
WScript.Sleep 1000
Set obj = ie.document.getElementsByTagName(“A”)
 For i = 0 To obj.Length
   If obj(i).innerText = “Testing Document” Then
      hr = obj(i).href
      Exit For
   End If
 Next

arrhr = Split(hr, “/”)
fname = arrhr(UBound(arrhr))
If hr <> “” Then
    strUrl = hr
    Des = “C:\Documents and Settings\Desktop\” & fname
   Set objXL = CreateObject(“Excel.Application”)
    With objXL.Application
        .Visible = False
        ‘Open the Workbook
        .Workbooks.Open “C:\Documents and Settings\Desktop\Download.xls”
        ‘Include CARMA in menu, run AutoOpen
        objXL.Application.DisplayAlerts = False
        x = .Run(“FileSave”, strUrl, Des)
    End With
    Set objXL = Nothing
MsgBox “Download Completed , the location of the saved file is->” & Des
End If

Set ie = Nothing

‘Special Thanks to Chandan Ray

November 8, 2010 Posted by | Uncategorized, VBScript and IE Automation | 3 Comments