If statement help on macro VBA - excel

Dim sDate As Date, eDate As Date, sTime As Date, eTime As Date
sTime = Sheet2.[B3]
eTime = Sheet2.[B4]
If sTime > eTime Then
Call pullInferred_Time(Sheet2.[B1], Sheet2.[B2], Sheet2.[B3], Sheet2.[B4], "Inferred_Time")
Call pullPPR(Sheet2.[B1], Sheet2.[B2], Sheet2.[B3], Sheet2.[B4])
Call pullPod_Gaps(Sheet2.[B1], Sheet2.[B8], Sheet2.[B5], Sheet2.[B6])
Call pullOOWA(Sheet2.[B1], Sheet2.[B8], Sheet2.[B5], Sheet2.[B6])
Call pullKiva_Scout(Sheet2.[B1], Sheet2.[B8], Sheet2.[B5], Sheet2.[B6])
Else
Call pullInferred_Time(Sheet2.[B1], Sheet2.[B2], Sheet2.[B3], Sheet2.[B4], "Inferred_Time")
Call pullPPR(Sheet2.[B1], Sheet2.[B2], Sheet2.[B3], Sheet2.[B4])
Call pullPod_Gaps(Sheet2.[B1], Sheet2.[B2], Sheet2.[B5], Sheet2.[B6])
Call pullOOWA(Sheet2.[B1], Sheet2.[B2], Sheet2.[B5], Sheet2.[B6])
Call pullKiva_Scout(Sheet2.[B1], Sheet2.[B2], Sheet2.[B5], Sheet2.[B6])
Sub pullPod_Gaps(sDate, eDate, sTime, eTime)
Dim H As New WinHttp.WinHttpRequest
Dim dataobj As New MSForms.DataObject
Dim URL As String
Dim html As New HTMLDocument
Dim htmlMetricTotals As HTMLHtmlElement
Dim htmlTable As HTMLHtmlElement
Dim htmlTBody As HTMLHtmlElement
Dim htmlTR As HTMLHtmlElement
Dim i As Integer
On Error Resume Next
i = 2
'sDate = ConvertFromLocalTimezoneToUTC(sDate)
'eDate = ConvertFromLocalTimezoneToUTC(eDate)
'sDate = toUnix(sDate)
'eDate = toUnix(eDate)
URL = "https://roboscout.amazon.com/view_plot_data/?sites=(LGB3" _
& ")&current_day=false&startDateTime=" & Format(sDate, "yyyy-mm-dd") _
& Format(sTime, "+hh%3A") _
& Format(sTime, "nn%3A00") _
& "&endDateTime=" & Format(eDate, "yyyy-mm-dd") _
& Format(eTime, "+hh%3A") _
& Format(eTime, "nn%3A00") _
& "&mom_ids=1443&osm_ids=977&oxm_ids=1131&ofm_ids=602&viz=nvd3Table&instance_id=0&object_id=20990&BrowserTZ=America%2FLos_Angeles&app_name=RoboScout&mode=CSV"
Debug.Print URL
H.SetAutoLogonPolicy 0
H.SetTimeouts 0, 0, 0, 0
H.Open "GET", URL, False
H.SetClientCertificate "CURRENT_USER\MY\" & Environ("USERNAME")
H.setRequestHeader "Cookie", VBAMidway_v1()
H.send
H.WaitForResponse
Debug.Print H.Status
Debug.Print H.responseText
dataobj.SetText H.responseText
dataobj.PutInClipboard
With Sheets("Pod_Gaps")
.Activate
.Cells.Clear
.Cells(1, 1).Select
.PasteSpecial Format:="Text", link:=False, DisplayAsIcon:=False, NoHTMLFormatting:=True
.Columns("A:A").TextToColumns DataType:=xlDelimited, ConsecutiveDelimiter:=False, Comma:=True, Space:=False
End With
End Sub
Sub pullOOWA(sDate, eDate, sTime, eTime)
Dim H As New WinHttp.WinHttpRequest
Dim dataobj As New MSForms.DataObject
Dim URL As String
Dim html As New HTMLDocument
Dim htmlMetricTotals As HTMLHtmlElement
Dim htmlTable As HTMLHtmlElement
Dim htmlTBody As HTMLHtmlElement
Dim htmlTR As HTMLHtmlElement
Dim i As Integer
On Error Resume Next
i = 2
'sDate = ConvertFromLocalTimezoneToUTC(sDate)
'eDate = ConvertFromLocalTimezoneToUTC(eDate)
'sDate = toUnix(sDate)
'eDate = toUnix(eDate)
URL = "https://roboscout.amazon.com/view_plot_data/?sites=(LGB3" _
& ")&startDateTime=" & Format(sDate, "yyyy-mm-dd") _
& Format(sTime, "+hh%3A") _
& Format(sTime, "nn%3A00") _
& "&endDateTime=" & Format(eDate, "yyyy-mm-dd") _
& Format(eTime, "+hh%3A") _
& Format(eTime, "nn%3A00") _
& "&mom_ids=2170%2C2168&osm_ids=1426&oxm_ids=2593&ofm_ids=1017&instance_id=0&object_id=21628&BrowserTZ=America%2FLos_Angeles&app_name=RoboScout&mode=CSV"
Debug.Print URL
H.SetAutoLogonPolicy 0
H.SetTimeouts 0, 0, 0, 0
H.Open "GET", URL, False
H.SetClientCertificate "CURRENT_USER\MY\" & Environ("USERNAME")
H.setRequestHeader "Cookie", VBAMidway_v1()
H.send
H.WaitForResponse
Debug.Print H.Status
Debug.Print H.responseText
dataobj.SetText H.responseText
dataobj.PutInClipboard
With Sheets("OOWA")
.Activate
.Cells.Clear
.Cells(1, 1).Select
.PasteSpecial Format:="Text", link:=False, DisplayAsIcon:=False, NoHTMLFormatting:=True
.Columns("A:A").TextToColumns DataType:=xlDelimited, ConsecutiveDelimiter:=False, Comma:=True, Space:=False
End With
End Sub
Sub pullKiva_Scout(sDate, eDate, sTime, eTime)
Dim H As New WinHttp.WinHttpRequest
Dim dataobj As New MSForms.DataObject
Dim URL As String
Dim html As New HTMLDocument
Dim htmlMetricTotals As HTMLHtmlElement
Dim htmlTable As HTMLHtmlElement
Dim htmlTBody As HTMLHtmlElement
Dim htmlTR As HTMLHtmlElement
Dim i As Integer
On Error Resume Next
i = 2
'sDate = ConvertFromLocalTimezoneToUTC(sDate)
'eDate = ConvertFromLocalTimezoneToUTC(eDate)
'sDate = toUnix(sDate)
'eDate = toUnix(eDate)
URL = "https://kivascout.amazon.com/view_plot_data/?sites=(LGB3" _
& ")&current_day=false&startDateTime=" & Format(sDate, "yyyy-mm-dd") _
& Format(sTime, "+hh%3A") _
& Format(sTime, "nn%3A") _
& "00&endDateTime=" _
& Format(eDate, "yyyy-mm-dd") _
& Format(eTime, "+hh%3A") _
& Format(eTime, "nn%3A") _
& "00&mom_ids=394%2C362%2C379%2C426&osm_ids=&oxm_ids=444&ofm_ids=&viz=nvd3Table&instance_id=1927&object_id=19851&BrowserTZ=America%2FLos_Angeles&app_name=RoboScout&mode=CSV"
Debug.Print URL
H.SetAutoLogonPolicy 0
H.SetTimeouts 0, 0, 0, 0
H.Open "GET", URL, False
H.SetClientCertificate "CURRENT_USER\MY\" & Environ("USERNAME")
H.setRequestHeader "Cookie", VBAMidway_v1()
H.send
H.WaitForResponse
Debug.Print H.Status
Debug.Print H.responseText
dataobj.SetText H.responseText
dataobj.PutInClipboard
With Sheets("Kiva_Scout")
.Activate
.Cells.Clear
.Cells(1, 1).Select
.PasteSpecial Format:="Text", link:=False, DisplayAsIcon:=False, NoHTMLFormatting:=True
.Columns("A:A").TextToColumns DataType:=xlDelimited, ConsecutiveDelimiter:=False, Comma:=True, Space:=False
End With
End Sub
Im kinda stuck here I need my code to be able to check to see if the value for sheet2.[B5] is greater than the value for Sheet2.[B6] then it will use the value for Sheet2.[B8] instead of the value in Sheet2.[B2] but only for the following calls(OOWA, Pod_gaps, Kiva_scout). sorry if I didn't write this well I'm new to VBA

Related

Automating MailMerge to create MailingLabels

I am trying to create mailinglabels using mailmerge but automated from my excel file.
Basically, I already have a template saved down as a word doc. My macro populates the worksheet called "Box" with the data needed on the label. Once populated, it calls on another sub to initiate the MailMerge Procedure. My code is breaking right at the start of the MailMerge.
here is my code:
Option Explicit
Sub CreateBox()
Dim LastRow As Long
Dim N As Integer
Dim nLastRow As Long
Dim nFirstRow As Long
Dim r As Range
LastRow = Track.Range("A" & Rows.Count).End(xlUp).Row
Set r = Track.UsedRange
nFirstRow = 2
Dim i As Long: i = 2
With ActiveSheet
On Error Resume Next
Application.ScreenUpdating = False
For N = nFirstRow To LastRow
If .Cells(N, "X") = "N" Then
.Cells(N, "B").Copy
Worksheets("Box").Cells(i, "A").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
.Cells(N, "X").Value = "Y"
.Cells(N, "D").Copy
Worksheets("Box").Cells(i, "B").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
.Cells(N, "F").Copy
Worksheets("Box").Cells(i, "C").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
.Cells(N, "E").Copy
Worksheets("Box").Cells(i, "D").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
.Cells(N, "A").Copy
Worksheets("Box").Cells(i, "E").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
.Cells(N, "T").Copy
Worksheets("Box").Cells(i, "F").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
i = i + 1
End If
Next
End With
Call mbrMailMerge
End Sub
Sub mbrMailMerge()
Dim Sheet As Worksheet, wsName As String, N As Long, dataSrc As String
Dim wdApp As New Word.Application, wdDoc As Word.Document
dataSrc = ActiveWorkbook.FullName
Const hDir As String = "C:\Users\nparker\Documents\Personal - NML\VLS" 'update filepath
wdApp.DisplayAlerts = wdAlertsNone
For N = 2 To Sheets.Count
wsName = Box.Name
Select Case wsName
Case "Box"
Set wdDoc = wdApp.Documents.Open(hDir & dataSrc & wsName & ".docx", AddToRecentFiles:=False)
Call Mailmerge(wdDoc, dataSrc, wsName)
Case Else
MsgBox "Could not find " & wsName & " Member Word Doc for Mail Merge. Please complete manually.", vbExclamation
End Select
Next
wdApp.DisplayAlerts = wdAlertsAll
wdApp.Visible = True
Set wdDoc = Nothing: Set wdApp = Nothing
End Sub
Sub Mailmerge(wdDoc As Word.Document, dataSrc As String, wsName As String)
dataSrc = ActiveWorkbook.FullName
With wdDoc
With .Mailmerge
.MainDocumentType = wdMailingLabels
.OpenDataSource Name:=dataSrc, ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _
AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:="", WritePasswordDocument:="", _
WritePasswordTemplate:="", Revert:=False, Format:=wdOpenFormatAuto, SubType:=wdMergeSubTypeAccess, _
Connection:="Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=dataSrc;Mode=Read;" & _
"Extended Properties=""HDR=YES;IME", SQLStatement:="SELECT * FROM `" & wsName & "$`", SQLStatement1:=""
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
.Destination = wdSendToNewDocument
End With
.Close SaveChanges:=False
End With
End Sub
.
With wdDoc
With .Mailmerge '<-----my code is breaking on this line
I am expecting the macro to open the specified word doc and import the data from the worksheet "box" but instead i get a
Run time error '91': Object variable or with block variable not set error
i found a better way of doing this, it is as follows:
Sub LabelMerge()
Dim oWord As Word.Application, oDoc As Word.Document
Dim sPath As String, I As Integer, oHeaders As Range
Dim LastCol As Long
Application.ScreenUpdating = False
LastCol = Rear.Cells(1, Columns.Count).End(xlToLeft).Column
Set oHeaders = Rear.Range(Rear.Cells(1, 1), Rear.Cells(1, LastCol))
sPath = ThisWorkbook.FullName
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.Documents.Add
oWord.Visible = True
oDoc.Mailmerge.MainDocumentType = wdMailingLabels
oWord.MailingLabel.CreateNewDocumentByID LabelID:="1359804772", _
Address:="", AutoText:="ToolsCreateLabels1", LaserTray:= _
wdPrinterManualFeed, ExtractAddress:=False, PrintEPostageLabel:=False, _
Vertical:=False
oDoc.Activate
With oDoc.Mailmerge.Fields
For I = 1 To oHeaders.Columns.Count
If oHeaders.Cells(1, I).Text = "Harvest Date 1" Then
oWord.Selection.TypeText Text:="H: "
.Add oWord.Selection.Range, Name:="Harvest_Date_1"
oWord.Selection.TypeText Text:=" J: "
ElseIf oHeaders.Cells(1, I).Text = "Julian Date 1:" Then
.Add oWord.Selection.Range, Name:="Julian_Date_1"
oWord.Selection.TypeParagraph
oWord.Selection.TypeText Text:="P: "
ElseIf oHeaders.Cells(1, I).Text = "Package Date" Then
.Add oWord.Selection.Range, Name:="Package_Date"
oWord.Selection.TypeText Text:=" T: "
ElseIf oHeaders.Cells(1, I).Text = "Team" Then
.Add oWord.Selection.Range, Name:="Team"
oWord.Selection.TypeParagraph
oWord.Selection.TypeText Text:="CBI ITEM CODE: "
ElseIf oHeaders.Cells(1, I).Text = "Product Code:" Then
.Add oWord.Selection.Range, Name:="Product_Code"
End If
oWord.Selection.TypeText " "
Next I
oWord.Selection.WholeStory
oWord.Selection.ParagraphFormat.LineSpacing = LinesToPoints(33008)
End With
oDoc.Mailmerge.OpenDataSource sPath
oWord.WordBasic.mailmergepropagatelabel
oDoc.Mailmerge.ViewMailMergeFieldCodes = False
oDoc.ActiveWindow.View.ShowFieldCodes = False
Set oDoc = Nothing
Set oWord = Nothing
Application.ScreenUpdating = True
End Sub
however, this code still requires the user to pick the sheet within the datasource. Is there another way of choosing the sheet in the code so the user doesn't have to be involved at all? Specifically this line:
oDoc.Mailmerge.OpenDataSource sPath

Improve VBA Code - it keeps word instance open after running

I have got an Excel-Code to generate singular word-mailmerged-documents.
It all work fine. The only problem is that after running the code and closing excel there is still one word instance running in the taskmanager.
Can someone help me fixing this?
My code so far is:
Private Sub CommandButton1_Click()
Dim wordApp As Word.Application
Dim wordTemplate As Word.Document
Dim wordMergedDoc As Word.MailMerge
Dim sourceBookPath As String
Dim sheetSourceName As String
Dim excelColumnFilter As String
Dim queryString As String
Dim baseQueryString As String
Dim wordTemplateDirectory As String
Dim wordTemplateFileName As String
Dim wordTemplateFullPath As String
Dim wordOutputDirectory As String
Dim wordOutputFileName As String
Dim wordOutputFullPath As String
Dim idListValues As Variant
Dim idValue As Integer
Dim idCounter As Integer
Dim recordCounter As Integer
Dim fileCounter As Integer
idListValues = Array(1, 2, 3, 4, 5, 6, 7)
sourceBookPath = ThisWorkbook.FullName
sheetSourceName = "Sheet1"
excelColumnFilter = "Anz"
baseQueryString = "SELECT * FROM `" & sheetSourceName & "$` where `" & excelColumnFilter & "` = [columFilterValue] order by `" & excelColumnFilter & "` ASC"
' Word:
wordTemplateDirectory = ThisWorkbook.Path & "\"
wordTemplateFileName = "sb[columFilterValue].docx"
wordOutputDirectory = ThisWorkbook.Path & "\"
wordOutputFileName = "MailMergeDifferent[columFilterValue]_[Record]"
Set wordApp = New Word.Application
wordApp.Visible = False
wordApp.DisplayAlerts = wdAlertsNone
MsgBox "Verteidigungsanzeigen werden erstellt, bitte kurz warten :)", vbOKOnly + vbInformation, "Information"
For idCounter = 0 To UBound(idListValues)
idValue = idListValues(idCounter)
queryString = Replace(baseQueryString, "[columFilterValue]", idValue)
wordTemplateFullPath = wordTemplateDirectory & Replace(wordTemplateFileName, "[columFilterValue]", idValue)
Set wordTemplate = wordApp.Documents.Open(wordTemplateFullPath)
Set wordMergedDoc = wordTemplate.MailMerge
With wordMergedDoc
.MainDocumentType = wdFormLetters
.OpenDataSource _
Name:=sourceBookPath, _
ReadOnly:=True, _
Format:=wdOpenFormatAuto, _
Revert:=False, _
AddToRecentFiles:=False, _
LinkToSource:=False, _
Connection:="Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;" & _
"Data Source=" & sourceBookPath & ";Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
SQLStatement:=queryString
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
For recordCounter = 1 To .DataSource.RecordCount
With .DataSource
.FirstRecord = wordMergedDoc.DataSource.ActiveRecord
.LastRecord = wordMergedDoc.DataSource.ActiveRecord
Dokumentenname = .DataFields("ID")
End With
.Execute Pause:=False
wordOutputFullPath = wordOutputDirectory & Replace(Replace(wordOutputFileName, "[columFilterValue]", idValue), "[Record]", recordCounter)
wordApp.ActiveDocument.SaveAs2 Filename:=wordOutputDirectory & Dokumentenname & ".docx", FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
wordApp.ActiveDocument.Close SaveChanges:=False
.DataSource.ActiveRecord = wdNextRecord
fileCounter = fileCounter + 1
Next recordCounter
End With
wordTemplate.Close False
Next idCounter
wordApp.Visible = False
Set wordApp = Nothing
MsgBox "Geschafft! Es wurden " & fileCounter & " Verteidigungsanzeigen erstellt", vbOKOnly + vbInformation, "Information"
End Sub
Try adding wordApp.Quit right before Set wordApp = Nothing

VBA recursive function get data only from new files.

Im using recursive function for getting specific data from files in folders and subfolders on my disk. This data are saved as a new row in my excel file and create the table. It works fine. But if I create new file and put it into random subfolder, after starting the recursive function, I want to add that data as new row in my table that was created before. Instead of removing whole table and then repeatedly start recursive function and get data in the table.
Something like refresh button - if I click on it, it will check every folder and subfolder and if find some new file or files, add them on the last row in the table.
This is the code I´m using now:
Function Recurse(sPath As String) As String
Dim FSO As New FileSystemObject
Dim myFolder As Folder
Dim mySubFolder As Folder
Dim myFile As File
Dim erow
Dim Black
Dim cislokabla
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
For Each myFile In mySubFolder.Files
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
GetData myFile, "Sheet1", _
"F1:F2", Sheets("Sheet1").Range(Cells(erow, 1), Cells(erow, 1)), True, False
Black = Sheet1.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
GetData myFile, "Sheet1", _
"O4:O5", Sheets("Sheet1").Range(Cells(Black, 2), Cells(Black, 2)), True, False
cislokabla = Sheet1.Cells(Rows.Count, 3).End(xlUp).Offset(1, 0).Row
GetData myFile, "Sheet1", _
"AH1:AH2", Sheets("Sheet1").Range(Cells(Black, 3), Cells(Black, 3)), True, False
Next
Recurse = Recurse(mySubFolder.Path)
Next
End Function
Sub nacitavaniedat()
Call Recurse("\\Sk-wftkabel\public\Identifikačné listy káblov\káble\")
End Sub
you need sheet2 named "Sheet2" to store filenames :)
(changed 30.01.14)
Sub Recurse()
Dim FSO As New FileSystemObject
Dim myFolder As Scripting.Folder, mySubFolder As Scripting.Folder
Dim myFile As File
Dim sPath$: sPath = "\\Sk-wftkabel\public\Identifikacne listy kablov\kable\"
Dim R$
R = Join(Application.Transpose(Sheets("Sheet2").UsedRange), "|")
Set myFolder = FSO.GetFolder(sPath)
For Each mySubFolder In myFolder.SubFolders
For Each myFile In mySubFolder.Files
DoEvents
If Not (InStr(1, R, myFile.Path) > 0) Then
GetData myFile, "Sheet1", "F1:F2", Sheets("Sheet1").Range(Sheets(1).Cells(Sheet1.Cells(Rows.Count, 1).End(xlUp).Row + 1, 1), Sheets(1).Cells(Sheet1.Cells(Rows.Count, 1).End(xlUp).Row + 1, 1)), True, False
GetData myFile, "Sheet1", "O4:O5", Sheets("Sheet1").Range(Sheets(1).Cells(Sheet1.Cells(Rows.Count, 2).End(xlUp).Row + 1, 2), Sheets(1).Cells(Sheet1.Cells(Rows.Count, 2).End(xlUp).Row + 1, 2)), True, False
GetData myFile, "Sheet1", "AH1:AH2", Sheets("Sheet1").Range(Sheets(1).Cells(Sheet1.Cells(Rows.Count, 3).End(xlUp).Row + 1, 3), Sheets(1).Cells(Sheet1.Cells(Rows.Count, 3).End(xlUp).Row + 1, 3)), True, False
Sheets("Sheet2").Cells(Sheets("Sheet2").UsedRange.Rows.Count + 1, 1).Value = myFile.Path
R = R & myFile.Path & "|"
End If
Next
Next
Set FSO = Nothing
Set myFolder = Nothing
Set mySubFolder = Nothing
Set myFile = Nothing
End Sub
Option Explicit
Public Sub GetData(SourceFile As Variant, SourceSheet As String, _
SourceRange As String, TargetRange As Range, Header As Boolean,
UseHeaderRow As Boolean)
' 30-Dec-2007, working in Excel 2000-2007
Dim rsCon As Object
Dim rsData As Object
Dim szConnect As String
Dim szSQL As String
Dim lCount As Long
' Create the connection string.
If Header = False Then
If Val(Application.Version) < 12 Then
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 8.0;HDR=No"";"
Else
szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 12.0;HDR=No"";"
End If
Else
If Val(Application.Version) < 12 Then
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes"";"
Else
szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & SourceFile & ";" & _
"Extended Properties=""Excel 12.0;HDR=Yes"";"
End If
End If
If SourceSheet = "" Then
' workbook level name
szSQL = "SELECT * FROM " & SourceRange$ & ";"
Else
' worksheet level name or range
szSQL = "SELECT * FROM [" & SourceSheet$ & "$" & SourceRange$ & "];"
End If
On Error GoTo SomethingWrong
Set rsCon = CreateObject("ADODB.Connection")
Set rsData = CreateObject("ADODB.Recordset")
rsCon.Open szConnect
rsData.Open szSQL, rsCon, 0, 1, 1
' Check to make sure we received data and copy the data
If Not rsData.EOF Then
If Header = False Then
TargetRange.Cells(1, 1).CopyFromRecordset rsData
Else
'Add the header cell in each column if the last argument is True
If UseHeaderRow Then
For lCount = 0 To rsData.Fields.Count - 1
TargetRange.Cells(1, 1 + lCount).Value = _
rsData.Fields(lCount).Name
Next lCount
TargetRange.Cells(2, 1).CopyFromRecordset rsData
Else
TargetRange.Cells(1, 1).CopyFromRecordset rsData
End If
End If
Else
MsgBox "No records returned from : " & SourceFile, vbCritical
End If
' Clean up our Recordset object.
rsData.Close
Set rsData = Nothing
rsCon.Close
Set rsCon = Nothing
Exit Sub
SomethingWrong:
MsgBox "The file name, Sheet name or Range is invalid of : " & SourceFile, _
vbExclamation, "Error"
On Error GoTo 0
End Sub

excel vba http request download data from yahoo finance

I am in the process of making a program I wrote using excel vba faster.
The program downloads stock market data from the asx.
I want to get data from 2 urls:
MY CODE
url2 = "http://ichart.finance.yahoo.com/table.txt?s=bhp.ax"
Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
XMLHTTP.Open "GET", url2, False
XMLHTTP.send
result = XMLHTTP.responseText
ActiveCell.Value = result
Set XMLHTTP = Nothing
URL 1. http://ichart.finance.yahoo.com/table.txt?s=bhp.ax
MY PROBLEM.
This file is very large. I thought I could simply store the result of these http requests and print it to the debug window or directly to a cell. However these methods seem to be cutting off parts of the data?
if I download the txt file from url 2 in notepad++ it has almost 200 000 characters
but it excel it has between 3 -5 000. What is the best way to handle these requests so that all the data is captured and I can parse it all later?
URL 2. from the first URL I only want the JSON data which results from the YQL query.
MY PROBLEM
I am not sure how to get just the json data when you follow the link below, and or how to store it so that the problem experienced with URL 1 (missing data) does not occur.
http://developer.yahoo.com/yql/console/?q=select%20symbol%2C%20ChangeRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22MSFT%22%29%20|%20sort%28field%3D%22ChangeRealtime%22%2C%20descending%3D%22true%22%29%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env#h=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22bhp.ax%22%29
Many Thanks, Josh.
Try this revised code
Sub GetYahooFinanceTable()
Dim sURL As String, sResult As String
Dim oResult As Variant, oData As Variant, R As Long, C As Long
sURL = "http://ichart.finance.yahoo.com/table.txt?s=bhp.ax"
Debug.Print "URL: " & sURL
sResult = GetHTTPResult(sURL)
oResult = Split(sResult, vbLf)
Debug.Print "Lines of result: " & UBound(oResult)
For R = 0 To UBound(oResult)
oData = Split(oResult(R), ",")
For C = 0 To UBound(oData)
ActiveSheet.Cells(R + 1, C + 1) = oData(C)
Next
Next
Set oResult = Nothing
End Sub
Function GetHTTPResult(sURL As String) As String
Dim XMLHTTP As Variant, sResult As String
Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
XMLHTTP.Open "GET", sURL, False
XMLHTTP.Send
Debug.Print "Status: " & XMLHTTP.Status & " - " & XMLHTTP.StatusText
sResult = XMLHTTP.ResponseText
Debug.Print "Length of response: " & Len(sResult)
Set XMLHTTP = Nothing
GetHTTPResult = sResult
End Function
This will split up the data into Rows so the max text length are not reached in a cell. Also this have further split the data with commas into corresponding columns.
You may like to try following code from http://investexcel.net/importing-historical-stock-prices-from-yahoo-into-excel/
I just modify the qurl variable to your url and it work, it pouring 4087 line of data to my excel sheet, nicely formatted without any problem.
Just name your sheet1 as Data.
Sub GetData()
Dim DataSheet As Worksheet
Dim EndDate As Date
Dim StartDate As Date
Dim Symbol As String
Dim qurl As String
Dim nQuery As Name
Dim LastRow As Integer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Sheets("Data").Cells.Clear
Set DataSheet = ActiveSheet
' StartDate = DataSheet.Range("startDate").Value
' EndDate = DataSheet.Range("endDate").Value
' Symbol = DataSheet.Range("ticker").Value
' Sheets("Data").Range("a1").CurrentRegion.ClearContents
' qurl = "http://ichart.finance.yahoo.com/table.csv?s=" & Symbol
' qurl = qurl & "&a=" & Month(StartDate) - 1 & "&b=" & Day(StartDate) & _
' "&c=" & Year(StartDate) & "&d=" & Month(EndDate) - 1 & "&e=" & _
' Day(EndDate) & "&f=" & Year(EndDate) & "&g=" & Sheets("Data").Range("a1") & "&q=q&y=0&z=" & _
' Symbol & "&x=.csv"
qurl = "http://ichart.finance.yahoo.com/table.txt?s=bhp.ax"
Debug.Print qurl
QueryQuote:
With Sheets("Data").QueryTables.Add(Connection:="URL;" & qurl, Destination:=Sheets("Data").Range("a1"))
.BackgroundQuery = True
.TablesOnlyFromHTML = False
.Refresh BackgroundQuery:=False
.SaveData = True
End With
Sheets("Data").Range("a1").CurrentRegion.TextToColumns Destination:=Sheets("Data").Range("a1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, other:=False
Sheets("Data").Columns("A:G").ColumnWidth = 12
LastRow = Sheets("Data").UsedRange.Row - 2 + Sheets("Data").UsedRange.Rows.Count
Sheets("Data").Sort.SortFields.Add Key:=Range("A2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With Sheets("Data").Sort
.SetRange Range("A1:G" & LastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
.SortFields.Clear
End With
End Sub
(the above is not my code, it was taken from the excel file they posted on investexcel.net link above)

Import multiple CSV files from Internet into Excel

I use this code to retrieve historical stock prices for about 40 tickers. I found it here http://www.mathfinance.cn/download-multiple-stock-quotes-from-yahoo-finance
It downloads about half of the symbols before a Run-time Error '1004' pops up. "Unable to open http://table.finance.yahoo.com/table.csv?s=Tickersymbol&a=11&b=21&c=1998 The internet site reports that the item you requested cannot be found (HTTP/1.0 404)
Can I change the code so this error won't happen? The code is below
Sub Get_Yahoo_finance()
Dim Sh As Worksheet
Dim Rng As Range
Dim Cell As Range
Dim Ticker As String
Dim StartDate As Date
Dim EndDate As Date
Dim a, b, c, d, e, f
Dim StrURL As String
Set Sh = Worksheets("Input")
Set Rng = Sh.Range("A2:A" & Sh.Range("A65536").End(xlUp).Row)
For Each Cell In Rng
Ticker = Cell.Value
StartDate = Cell.Offset(0, 1).Value
EndDate = Cell.Offset(0, 2).Value
a = Format(Month(StartDate) - 1, "00") ' Month minus 1
b = Day(StartDate)
c = Year(StartDate)
d = Format(Month(EndDate) - 1, "00")
e = Day(EndDate)
f = Year(EndDate)
StrURL = "URL;http://table.finance.yahoo.com/table.csv?"
StrURL = StrURL & "s=" & Ticker & "&a=" & a & "&b=" & b
StrURL = StrURL & "&c=" & c & "&d=" & d & "&e=" & e
StrURL = StrURL & "&f=" & f & "&g=d&ignore=.csv"
If WorksheetExists(Ticker, ActiveWorkbook) Then
Application.DisplayAlerts = False
Sheets(Ticker).Select
ActiveWindow.SelectedSheets.Delete
ActiveWorkbook.Worksheets.Add.Name = Ticker
Else
ActiveWorkbook.Worksheets.Add.Name = Ticker
End If
With ActiveSheet.QueryTables.Add(Connection:=StrURL, Destination:=Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlAllTables
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.Refresh BackgroundQuery:=False
End With
Columns("A:A").TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
:=Array(Array(1, 4), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
Array(7, 1))
Range("A2").Select
Range(Selection, Selection.End(xlDown)).NumberFormat = "d-mmm-yy"
Columns("A:F").EntireColumn.AutoFit
Next Cell
End Sub
Function WorksheetExists(SheetName As String, _
Optional WhichBook As Workbook) As Boolean
'from Chip Pearson
Dim WB As Workbook
Set WB = IIf(WhichBook Is Nothing, ThisWorkbook, WhichBook)
On Error Resume Next
WorksheetExists = CBool(Len(WB.Worksheets(SheetName).Name) > 0)
End Function
EDIT: The code below fixes the issue you reported but runs out of memory very quickly. I have created another answer which I think is much better and robust
It looks like your query is not recognised by the server. You can add some error checks to continue if such an error is encountered.
Sub Get_Yahoo_finance()
Dim Sh As Worksheet
Dim Rng As Range
Dim Cell As Range
Dim Ticker As String
Dim StartDate As Date
Dim EndDate As Date
Dim a, b, c, d, e, f
Dim StrURL As String
Dim errorMsg As String
Set Sh = Worksheets("Input")
Set Rng = Sh.Range("A2:A" & Sh.Range("A65536").End(xlUp).Row)
For Each Cell In Rng
Ticker = Cell.Value
StartDate = Cell.Offset(0, 1).Value
EndDate = Cell.Offset(0, 2).Value
a = Format(Month(StartDate) - 1, "00") ' Month minus 1
b = Day(StartDate)
c = Year(StartDate)
d = Format(Month(EndDate) - 1, "00")
e = Day(EndDate)
f = Year(EndDate)
StrURL = "URL;http://table.finance.yahoo.com/table.csv?"
StrURL = StrURL & "s=" & Ticker & "&a=" & a & "&b=" & b
StrURL = StrURL & "&c=" & c & "&d=" & d & "&e=" & e
StrURL = StrURL & "&f=" & f & "&g=d&ignore=.csv"
If WorksheetExists(Ticker, ActiveWorkbook) Then
Application.DisplayAlerts = False
Sheets(Ticker).Select
ActiveWindow.SelectedSheets.Delete
ActiveWorkbook.Worksheets.Add.Name = Ticker
Else
ActiveWorkbook.Worksheets.Add.Name = Ticker
End If
With ActiveSheet.QueryTables.Add(Connection:=StrURL, Destination:=Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlAllTables
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
On Error Resume Next
.Refresh BackgroundQuery:=False
errorMsg = IIf(Err.Number = 0, "", Err.Description)
On Error GoTo 0
End With
If errorMsg = "" Then
Columns("A:A").TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
:=Array(Array(1, 4), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
Array(7, 1))
Range("A2").Select
Range(Selection, Selection.End(xlDown)).NumberFormat = "d-mmm-yy"
Columns("A:F").EntireColumn.AutoFit
Else
Range("A1") = errorMsg
End If
Next Cell
End Sub
Function WorksheetExists(SheetName As String, Optional WhichBook As Workbook) As Boolean '
'from Chip Pearson
Dim WB As Workbook
Set WB = IIf(WhichBook Is Nothing, ThisWorkbook, WhichBook)
On Error Resume Next
WorksheetExists = CBool(Len(WB.Worksheets(SheetName).Name) > 0)
End Function
You might want to delete the sheet instead of putting an error message in it or maybe send a MsgBox instead...
I can't get your method to work properly (I get out of memory errors after a few 100s of tickers).
So I got interested and dug a bit further. I propose another approach below which is more complex but yields better results (I uploaded the 500 stocks of the S&P in 3 minutes (about 3 seconds for the actual job in Excel, the rest is connection / download time). Just copy paste the whole code in a module and run the runBatch procedure.
Option Explicit
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMillisecond As Long)
Private Declare Function URLDownloadToCacheFile Lib "urlmon" _
Alias "URLDownloadToCacheFileA" (ByVal lpUnkcaller As Long, _
ByVal szURL As String, ByVal szFileName As String, _
ByVal dwBufLength As Long, ByVal dwReserved As Long, _
ByVal IBindStatusCallback As Long) As Long
Public Sub runBatch()
'Assumes there is a sheet called "Input" with 3 columns:
'Ticker, Start Date, End Date
'Actual data starts from Row 2
Dim tickerData As Variant
Dim ticker As String
Dim url As String
Dim i As Long
Dim yahooData As Variant
On Error GoTo error_handler
Application.ScreenUpdating = False
tickerData = Sheets("Input").UsedRange
For i = LBound(tickerData, 1) + 1 To UBound(tickerData, 1) 'skip first row
ticker = tickerData(i, 1)
url = getYahooUrl(ticker, tickerData(i, 2), tickerData(i, 3))
yahooData = getCsvContent(url)
If isArrayEmpty(yahooData) Then
MsgBox "No data found for " + ticker
Else
copyDataToSheet yahooData, ticker
End If
Next i
Application.ScreenUpdating = True
Exit Sub
error_handler:
MsgBox "Error found while reading ticker [" + ticker + "]: " + Err.Description
Application.ScreenUpdating = True
End Sub
Private Function getYahooUrl(ByVal ticker As String, ByVal startDate As Date, ByVal endDate As Date) As String
Dim a As String
Dim b As String
Dim c As String
Dim d As String
Dim e As String
Dim f As String
a = Format(Month(startDate) - 1, "00") ' Month minus 1
b = Day(startDate)
c = Year(startDate)
d = Format(Month(endDate) - 1, "00")
e = Day(endDate)
f = Year(endDate)
getYahooUrl = "http://table.finance.yahoo.com/table.csv?" & _
"s=" & ticker & "&" & _
"a=" & a & "&" & _
"b=" & b & "&" & _
"c=" & c & "&" & _
"d=" & d & "&" & _
"e=" & e & "&" & _
"f=" & f & "&" & _
"g=d&ignore=.csv"
End Function
Private Function getCsvContent(url As String) As Variant
Const RETRY_NUMS As Long = 3 'How m any times do we retry the download before giving up
Dim szFileName As String
Dim i As Long
For i = 1 To RETRY_NUMS
szFileName = Space$(300)
If URLDownloadToCacheFile(0, url, szFileName, Len(szFileName), 0, 0) = 0 Then
getCsvContent = getDataFromFile(Trim(szFileName), ",")
Kill Trim(szFileName) 'to make sure data is refreshed next time
Exit Function
End If
Sleep (500)
Next i
End Function
Private Sub copyDataToSheet(data As Variant, sheetName As String)
If Not WorksheetExists(sheetName) Then
Worksheets.Add.Name = sheetName
End If
With Sheets(sheetName)
.Cells.ClearContents
.Cells(1, 1).Resize(UBound(data, 1), UBound(data, 2)) = data
.Columns(1).NumberFormat = "d-mmm-yy"
.Columns("A:F").AutoFit
End With
End Sub
Private Function WorksheetExists(sheetName As String, Optional WhichBook As Workbook) As Boolean '
'from Chip Pearson
Dim WB As Workbook
Set WB = IIf(WhichBook Is Nothing, ThisWorkbook, WhichBook)
On Error Resume Next
WorksheetExists = CBool(Len(WB.Worksheets(sheetName).Name) > 0)
End Function
Private Function isArrayEmpty(parArray As Variant) As Boolean
'Returns false if not an array or dynamic array that has not been initialised (ReDim) or has been erased (Erase)
If IsArray(parArray) = False Then isArrayEmpty = True
On Error Resume Next
If UBound(parArray) < LBound(parArray) Then isArrayEmpty = True: Exit Function Else: isArrayEmpty = False
End Function
Private Function getDataFromFile(parFileName As String, parDelimiter As String, Optional parExcludeCharacter As String = "") As Variant 'V.20081021
'parFileName is supposed to be a delimited file (csv...)
'Returns an empty array if file is empty or can't be opened
'20081021: number of columns based on the line with the largest number of columns, not on the first line
' parExcludeCharacter: sometimes csv files have quotes around strings: "XXX" - if parExcludeCharacter = """" then removes the quotes
'20081022: Error Checks in place
Dim locLinesList() As Variant
Dim locData As Variant
Dim i As Long
Dim j As Long
Dim locNumRows As Long
Dim locNumCols As Long
Dim fso As Variant
Dim ts As Variant
Const REDIM_STEP = 10000
Set fso = CreateObject("Scripting.FileSystemObject")
On Error GoTo error_open_file
Set ts = fso.OpenTextFile(parFileName)
On Error GoTo unhandled_error
'Counts the number of lines and the largest number of columns
ReDim locLinesList(1 To 1) As Variant
i = 0
Do While Not ts.AtEndOfStream
If i Mod REDIM_STEP = 0 Then
ReDim Preserve locLinesList(1 To UBound(locLinesList, 1) + REDIM_STEP) As Variant
End If
locLinesList(i + 1) = Split(ts.ReadLine, parDelimiter)
j = UBound(locLinesList(i + 1), 1) 'number of columns
If locNumCols < j Then locNumCols = j
i = i + 1
Loop
ts.Close
locNumRows = i
If locNumRows = 0 Then Exit Function 'Empty file
ReDim locData(1 To locNumRows, 1 To locNumCols + 1) As Variant
'Copies the file into an array
If parExcludeCharacter <> "" Then
For i = 1 To locNumRows
For j = 0 To UBound(locLinesList(i), 1)
If Left(locLinesList(i)(j), 1) = parExcludeCharacter Then
If Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
locLinesList(i)(j) = Mid(locLinesList(i)(j), 2, Len(locLinesList(i)(j)) - 2) 'If locTempArray = "", Mid returns ""
Else
locLinesList(i)(j) = Right(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
End If
ElseIf Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
locLinesList(i)(j) = Left(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
End If
locData(i, j + 1) = locLinesList(i)(j)
Next j
Next i
Else
For i = 1 To locNumRows
For j = 0 To UBound(locLinesList(i), 1)
locData(i, j + 1) = locLinesList(i)(j)
Next j
Next i
End If
getDataFromFile = locData
Exit Function
error_open_file: 'returns empty variant
unhandled_error: 'returns empty variant
End Function
I ran it once and it failed. Put a breakpoint on the query line, loaded the yahoo address into my browser to make sure it was valid, then the script worked. I also made sure that there were no other worksheets in the project. Here's a screenshot of the VBA editor and where the breakpoint goes:
You can stick the variable into a watch window and then fool around with it to see what it does. If you come up with any applications for this I'd love to hear about them!
Attached is a "simpler" solution using the original code modified to retry retrieving the ticker data upto 3 times (waiting a few seconds between attempts) before finally admitting failure by messagebox. My 2 cents :-)
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMillisecond As Long)
Sub Get_Yahoo_finance_history()
Dim Sh As Worksheet
Dim Rng As Range
Dim Cell As Range
Dim Ticker As String
Dim StartDate As Date
Dim EndDate As Date
Dim a, b, c, d, e, f
Dim StrURL As String
Dim RetryCount As Integer
'turn calculation off
'Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Set Sh = Worksheets("Input")
Set Rng = Sh.Range("A2:A" & Sh.Range("A65536").End(xlUp).Row)
For Each Cell In Rng
Ticker = Cell.Value
StartDate = Cell.Offset(0, 1).Value
EndDate = Cell.Offset(0, 2).Value
a = Format(Month(StartDate) - 1, "00") ' Month minus 1
b = Day(StartDate)
c = Year(StartDate)
d = Format(Month(EndDate) - 1, "00")
e = Day(EndDate)
f = Year(EndDate)
StrURL = "URL;http://table.finance.yahoo.com/table.csv?"
StrURL = StrURL & "s=" & Ticker & "&a=" & a & "&b=" & b
StrURL = StrURL & "&c=" & c & "&d=" & d & "&e=" & e
StrURL = StrURL & "&f=" & f & "&g=d&ignore=.csv"
If WorksheetExists(Ticker, ActiveWorkbook) Then
Sheets(Ticker).Select
ActiveWindow.SelectedSheets.Delete
ActiveWorkbook.Worksheets.Add.Name = Ticker
Else
ActiveWorkbook.Worksheets.Add.Name = Ticker
End If
RetryCount = 0 Retry:
If RetryCount > 3 Then
Range("A1") = errorMsg
MsgBox "After 3 attempts: Could not retrieve data for " + Ticker
End
End If
RetryCount = RetryCount + 1
With ActiveSheet.QueryTables.Add(Connection:=StrURL, Destination:=Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlAllTables
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
On Error Resume Next
.Refresh BackgroundQuery:=False
errorMsg = IIf(Err.Number = 0, "", Err.Description)
On Error GoTo 0
End With
If errorMsg = "" Then
Columns("A:A").TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
:=Array(Array(1, 4), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
Array(7, 1))
Columns("A").EntireColumn.NumberFormat = "mm/dd/yyyy"
Columns("B:E").EntireColumn.NumberFormat = "$###,##0.00"
Columns("F").EntireColumn.NumberFormat = "###,##0"
Columns("B:E").EntireColumn.NumberFormat = "$###,##0.00"
Columns("A:F").EntireColumn.AutoFit
Else
Sleep (500)
Sheets(Ticker).Cells.ClearContents
GoTo Retry
End If
Next Cell
'turn calculation back on
'Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
End Sub
Function WorksheetExists(SheetName As String, _
Optional WhichBook As Workbook) As Boolean
'from Chip Pearson
Dim WB As Workbook
Set WB = IIf(WhichBook Is Nothing, ThisWorkbook, WhichBook)
On Error Resume Next
WorksheetExists = CBool(Len(WB.Worksheets(SheetName).Name) > 0)
End Function

Resources