Simple VBA help to download data from URL

Sir,

Thank you for your suggestion. I never knew about F9 and it was quite interesting to debug the code. After following your suggestions i found out the following from locals window.

: sExtractFileName : "cm28DEC2011bhav.csv.zip" : String

: vFile : Empty : Variant/Empty

: aName : Empty : Variant/Empty

: vFolderName : Empty : Variant/Empty

: vSaveFileName : Empty : Variant/Empty

The actual file was downloaded to " E:\Macros\Input "

After the following Line the code is returning to Else statement

Code:
For Each vFile In oApp.Namespace(aURLs(i, 4)).items

Please see if this data is enough to find out why the code is not extracting the downloaded .zip files.

and moreover i am using Windows 7 if that matters.

Regards,
Zaska
 
Upvote 0

Excel Facts

Enter current date or time
Ctrl+: enters current time. Ctrl+; enters current date. Use Ctrl+: Ctrl+; Enter for current date & time.
Does it work correctly if you try and change the path to the C drive? I'm wondering if maybe it's not working in lieu of going across drives. If so, we can make a workaround by transferring it to the C drive, then copying the files to the destination folder, then deleting the originals.

EDIT: The above information is good, but is somewhat irrelevant towards the current problem. Good to know though. I didn't take the variable declarations out that weren't used anymore, so that is why there are some variables which say they are empty, because I put them into an array afterwards to handle multiple websites.
 
Upvote 0
Sir,


I tried the following

Code:
   aURLs(i, 3) = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\"

   aURLs(i, 3) = "C:\Macros\Input\"
In both the above case .zip files were not extracted as .csv files . Finally i would like to request you one thing. Let all the files get downloaded first and for that i made the following changes.

Code:
 'sFilename
        aURLs(i, 1) = sFileName
    'aNames
        aURLs(i, 2) = Split(sFileName, "/")
    'vFolderName
        aURLs(i, 3) = "E:\Macros\Input\"
    'vSaveFileName
        aURLs(i, 4) = aURLs(i, 3) & aURLs(i, 2)(UBound(Split(sFileName, "/")))

    'Check if the file exists locally in this location first
        If Len(Dir(CStr(aURLs(i, 4)), vbNormal)) = 0 Then
    'Download the file first to the Desktop
            ret = URLDownloadToFile(0, aURLs(i, 1), aURLs(i, 4), 0, 0)
    'See if the download happened correctly
            If ret = 0 Then
    'all went well
            Else
    'Something went wrong, grab the URL and pass for error messaging
    '            sErr = sErr & Format(dtLook, "mmm d, yyyy") & NL
                sErr = sErr & aURLs(i, 1) & NL
                Exit Sub
            End If
        Else
            If MsgBox("The file is already downloaded.  Continue anyway?", vbYesNo, "CONTINUE?") <> vbYes Then Exit Sub
        End If
        
  [COLOR=Red] Next i[/COLOR]
After downloading all the files from web the "E:\Macros\Input\ " folder has four .zip files and is it possible to extract them all ? and i noticed that if i turn the following as True

Const CLEANUP As Boolean = True

I couldn't see any of the .zip files , i could see only the .DAT file in "E:\Macros\Input\" Folder. So the code is recognising .zip files but why not it is extracting them from that folder?


Anyway i don't like to trouble you more and you have provided me a valuable code. Extracting .zip files can be done manually so it's not a big problem.

Thank you for all your support and have a great day.

Regards,
Zaska
 
Last edited:
Upvote 0
Hi, sorry I didn't see your post. Thanks for the friendly 'reminder'. :)

I'm not sure why it's not working. Perhaps we need to change the drive? I have made that addition to this code and set the cleanup to False as well. This is the standard module code...


VBA Code:
Option Explicit

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

Public WB As Workbook
Public WS As Worksheet
Public i As Long
Public sErr As String

Public Const NL As String = vbNewLine
Public Const DNL As String = vbNewLine & vbNewLine

Sub LaunchUserform()
    Load ufGetData
    ufGetData.Show
End Sub

Sub UnzipFile(dtLook As Date)

'Set CLEANUP to True to delete zip file after extraction
'Leave as False to not delete zip file after extraction
    Const CLEANUP As Boolean = False

    'Variable declaration
    Dim oApp As Object
    Dim vFile As Variant
    Dim sFileName As Variant
    Dim aName As Variant
    Dim vFolderName As Variant
    Dim vSaveFileName As Variant
    Dim sDay As String
    Dim sMonth As String
    Dim sYear As String
    Dim sDate As String
    Dim sExtractFileName As String
    Dim ret As Long
    Dim iMonth As Long
    Dim aURLs(1 To 5, 1 To 4) As Variant

    'Set file name variables
    sDay = CStr(Format(Day(dtLook), "00"))
    sMonth = UCase(CStr(MonthName(Month(dtLook), True)))
    iMonth = CStr(Format(Month(dtLook), "00"))
    sYear = CStr(Year(dtLook))
    sDate = Format(Day(dtLook), "00") & sMonth & sYear

    'EXAMPLES:
    'http://www.nseindia.com/content/historical/EQUITIES/2010/SEP/cm20SEP2010bhav.csv.zip
    'http://www.nseindia.com/content/historical/DERIVATIVES/2009/SEP/fo18SEP2009bhav.csv.zip
    'http://www.bseindia.com/bhavcopy/eq180909_csv.zip
    'http://www.bseindia.com/BSEDATA/gross/2009/SCBSEALL1809.zip
    'http://www.nseindia.com/archives/equities/mto/MTO_18092009.DAT

    'Loop through all 5 websites
    For i = 1 To 5
        Select Case i
        Case 1
            sFileName = "http://www.nseindia.com/content/historical/EQUITIES/" & sYear & "/" & sMonth & "/cm" & sDate & "bhav.csv.zip"
        Case 2
            sFileName = "http://www.nseindia.com/content/historical/DERIVATIVES/" & sYear & "/" & sMonth & "/fo" & sDate & "bhav.csv.zip"
        Case 3
            sFileName = "http://www.bseindia.com/bhavcopy/eq" & Format(dtLook, "ddmmyy") & "_csv.zip"
        Case 4
            sFileName = "http://www.bseindia.com/BSEDATA/gross/" & sYear & "/SCBSEALL" & sDay & iMonth & ".zip"
        Case 5
            sFileName = "http://www.nseindia.com/archives/equities/mto/MTO_" & sDay & iMonth & sYear & ".DAT"
        End Select

        ChDrive "E"

        'sFilename
        aURLs(i, 1) = sFileName
        'aNames
        aURLs(i, 2) = Split(sFileName, "/")
        'vFolderName
        aURLs(i, 3) = "E:\Macros\Input\"
        ' aURLs(i, 3) = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\"
        'vSaveFileName
        aURLs(i, 4) = aURLs(i, 3) & aURLs(i, 2)(UBound(Split(sFileName, "/")))

        'Check if the file exists locally in this location first
        If Len(Dir(CStr(aURLs(i, 4)), vbNormal)) = 0 Then
            'Download the file first to the Desktop
            ret = URLDownloadToFile(0, aURLs(i, 1), aURLs(i, 4), 0, 0)
            'See if the download happened correctly
            If ret = 0 Then
                'all went well
            Else
                'Something went wrong, grab the URL and pass for error messaging
                ' sErr = sErr & Format(dtLook, "mmm d, yyyy") & NL
                sErr = sErr & aURLs(i, 1) & NL
                Exit Sub
            End If
        Else
            If MsgBox("The file is already downloaded. Continue anyway?", vbYesNo, "CONTINUE?") <> vbYes Then Exit Sub
        End If

        'Check if it is a zip file, if so, extract it
        If UCase(Right(aURLs(i, 4), 4)) = ".ZIP" Then

            'Set extraction name (same of file, less the ".zip" at the end)
            sExtractFileName = Split(aURLs(i, 4), "\")(UBound(Split(aURLs(i, 4), "\")))
            sExtractFileName = Left(sExtractFileName, Len(sExtractFileName) - 4)

            'Do the actual extraction
            Set oApp = CreateObject("Shell.Application")
            For Each vFile In oApp.Namespace(aURLs(i, 4)).items
                If Len(Dir(CStr(vFile), vbNormal)) <> 0 Then
                    If MsgBox(CStr(vFile) & " already exists. Delete and replace?", vbYesNo, "REPLACE?") = vbYes Then
                        Kill aURLs(i, 3) & CStr(vFile)
                        oApp.Namespace(aURLs(i, 3)).CopyHere oApp.Namespace(aURLs(i, 4)).items.Item(CStr(vFile))
                    End If
                Else
                    oApp.Namespace(aURLs(i, 3)).CopyHere oApp.Namespace(aURLs(i, 4)).items.Item(CStr(vFile))
                End If
                ' oApp.Namespace(vFolderName).CopyHere oApp.Namespace(vSaveFileName).items.Item(CStr(vFile))
            Next vFile

            'Clean up zip files
            If CLEANUP Then
                Kill aURLs(i, 4)
            End If

        End If

    Next i

    ChDrive "C"

End Sub

Public Sub TOGGLEEVENTS(blnState As Boolean)
'Originally written by Zack Barresse
    With Application
        If Not blnState And Not ActiveWorkbook Is Nothing Then .Calculation = xlCalculationManual
        .DisplayAlerts = blnState
        .EnableEvents = blnState
        .ScreenUpdating = blnState
        If blnState Then .CutCopyMode = False
        If blnState Then .StatusBar = False
        If blnState And Not ActiveWorkbook Is Nothing Then .Calculation = xlCalculationAutomatic
    End With
End Sub


Try that and see if it works for you.
 
Last edited:
Upvote 0
Hi Zack,I couldnt find the attachment in the thread. Could you pls send it to thanks
 
Last edited by a moderator:
Upvote 0
Hi Amber, I'm not sure I follow. There isn't an attachment. The idea is for you to copy the code and paste it on your end.
 
Upvote 0
Zack, In the post number 8 on Dec 21st, 2011, 02:15 PM you had mentioned that test file attached in zip format. so we hoped you had attached the test file with all macro in it. Could you please either attach the working file. Thanks in advance
 
Last edited by a moderator:
Upvote 0
@john302928
I removed your email address from your post, as Spam Bots routinely troll Public User Forums like these looking for email addresses to Spam.
 
Upvote 0

Forum statistics

Threads
1,225,135
Messages
6,183,065
Members
453,147
Latest member
Lacey D

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top