VBA Stock info retrieval into Excel - vba

first off, I have to admit I'm not very good at VBA. I've tried to adapt the code from this and this site to download the information I need on a list of given stock tickers. I have a list of the tickers in column A of sheet "data" and want the downloaded infos (name, exchange, bid, ask, etc.) in the columns to the right, starting in column c. I want to run the macro (and thus update all values) with a click on a button.
I tried to adapt the code accordingly but keep on running into errors I cannot debug. Can you experts help me get the code right?
Thanks so much in advance!
Error
Sub DownloadStockQuotes(ByVal stockTicker As String, ByVal DestinationCell As String)
Dim qurl As String
Dim StartMonth, StartDay, StartYear, EndMonth, EndDay, EndYear As String
Dim C As WorkbookConnection
StartMonth = Format(Month(StartDate) - 1, "00")
StartDay = Format(Day(StartDate), "00")
StartYear = Format(Year(StartDate), "00")
EndMonth = Format(Month(EndDate) - 1, "00")
EndDay = Format(Day(EndDate), "00")
EndYear = Format(Year(EndDate), "00")
qurl = "URL;http://finance.yahoo.com/d/quotes.csv?s=" + stockTicker + "&f=nxj1b4abc1p2"
On Error GoTo ErrorHandler:
With ActiveSheet.QueryTables.Add(Connection:=qurl, Destination:=Range(DestinationCell))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
' .PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
' .RefreshPeriod = 0
' .WebSelectionType = xlSpecifiedTables
' .WebFormatting = xlWebFormattingNone
' .WebTables = "20"
' .WebPreFormattedTextToColumns = True
' .WebConsecutiveDelimitersAsOne = True
' .WebSingleBlockTextImport = False
' .WebDisableDateRecognition = False
' .WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
ErrorHandler:
End Sub
Sub DownloadData()
Dim frequency As String
Dim numRows As Integer
Dim lastRow As Integer
Dim lastErrorRow As Integer
Dim lastSuccessRow As Integer
Dim stockTicker As String
Application.ScreenUpdating = False
lastRow = Worksheets("Kursabruf").Cells(Rows.Count, "a").End(xlUp).Row
'Loop through all tickers
For ticker = 2 To lastRow
stockTicker = Worksheets("Kursabruf").Range("$a$" & ticker)
If stockTicker = "" Then
GoTo NextIteration
End If
Call DownloadStockQuotes(stockTicker, "$c$2")
Worksheets("Kursabruf").Columns("c:c").TextToColumns Destination:=Range("c2"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
DecimalSeparator:=".", ThousandsSeparator:=" ", _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1))
Sheets(stockTicker).Columns("A:G").ColumnWidth = 10
lastRow = Sheets(stockTicker).UsedRange.Row - 2 + Sheets(stockTicker).UsedRange.Rows.Count
GoTo NextIteration
'Delete final blank row otherwise will get ,,,, at bottom of CSV
Sheets("Kursabruf").Rows(lastRow + 1 & ":" & Sheets("Kursabruf").Rows.Count).Delete
NextIteration:
Next ticker
Application.DisplayAlerts = False
ErrorHandler:
Worksheets("Parameters").Select
For Each C In ThisWorkbook.Connections
C.Delete
Next
End Sub

Related

Excel macro for converting fix length text file to delimited separated with substring function

this is the code i am using and its working fine but for one row only .I need to make it generic to apply it on all rows of the text file.I have total 150 rows in text file.How can i loop it while making next line as end of record.
Code:
Public Sub Convert_TxtFile()
Dim myStr As String
myStr = FileText("C:\Users\BS255028\Desktop\Book2.txt")
Cells(1, 1) = Mid(myStr, 1, 4)
Cells(1, 2) = Mid(myStr, 5, 3)
Cells(1, 3) = Mid(myStr, 8, 8)
Cells(1, 4) = Mid(myStr, 16, 2)
End Sub
Function FileText(ByVal filename As String) As String
Dim nFileNum As Integer
If Len(Dir$(filename)) = 0 Then
Err.Raise 53
End If
nFileNum = FreeFile
Open filename$ For Binary As #nFileNum
FileText = Space$(LOF(nFileNum))
Get #nFileNum, , FileText
Close #nFileNum
End Function
You could simply record a macro of you importing the text file. Using fixed widths will allow you to split the text into columns based on the desired widths.
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\BS255028\Desktop\Book2.txt", _
Destination:=Range("$A$1"))
.Name = "adam_styborskis_pauper_cube"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileFixedColumnWidths = Array(4, 3, 8, 2)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Untested:
Public Sub Convert_TxtFile()
Dim myStr As String, s, arr, i As Long
myStr = FileText("C:\Users\BS255028\Desktop\Book2.txt")
arr = Split(myStr, vbCrLf)
i = 1
for each s in arr
Cells(i, 1).Resize(1, 4) = Array(Mid(myStr, 1, 4), Mid(myStr, 5, 3), _
Mid(myStr, 8, 8), Mid(myStr, 16, 2))
i = i + 1
next
End Sub
Not sure how FileText works, but if it puts the text in to 150 rows in Excel, you can just add a loop:
Public Sub Convert_TxtFile()
Dim myStr As String
Dim i as Long
myStr = FileText("C:\Users\BS255028\Desktop\Book2.txt")
For i = 1 to 150
Cells(i, 1) = Mid(myStr, 1, 4)
Cells(i, 2) = Mid(myStr, 5, 3)
Cells(i, 3) = Mid(myStr, 8, 8)
Cells(i, 4) = Mid(myStr, 16, 2)
Next i
End Sub

Remove return key or newline in txt file before import in excel (vba)

I have a vba script that brings in a .csv file and sorts it in excel. However there are some carriage returns on the end column and this is adding newlines in the import. I can fix this manually by going to the text file and replacing \n with "". But i would like this to be done automatically in the script before it is imported.
Here is my current script to import the text file:
For rep1 = 8 To 8
Dim i As Integer, j As Integer, pctCompl As Integer, myint As Integer
Dim lastrow As Long
Dim ws As Worksheet, ws1 As Worksheet, ws2 As Worksheet
Dim file_name As String
Dim file_name2 As String
Dim row_number As String
Dim output_sheet As String
Dim hour As String
Dim day As String
Dim month As String
Dim project As String
Set ws = Worksheets("Master")
Set ws1 = Worksheets("RAW_Data")
Set ws2 = Worksheets("BOM")
file_name = Sheets("Master").Range("F" & rep1).Value
file_name2 = Sheets("Master").Range("G" & rep1).Value
output_sheet = Sheets("Master").Range("L" & rep1).Value
row_number = Sheets("Master").Range("M" & rep1).Value
hour = Format(Sheets("Master").Range("I" & rep1).Value, "00")
day = Sheets("Master").Range("K" & rep1).Value
month = Sheets("Master").Range("J" & rep1).Value
project = Sheets("Master").Range("B2").Value
ws1.Activate
Columns("A:A").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Delete Shift:=xlToLeft
ws.Activate
aa = file_name2 & Format(Date, "yyyymmdd") & "_" & Format(Time, "Hh")
With Sheets(output_sheet).QueryTables.Add(Connection:="TEXT;" + file_name + "\" + month + "\" + day + "\" + file_name2 & Format(Date, "yyyymmdd") & "_" & hour & ".txt", Destination:=Sheets(output_sheet).Range("$A$" + row_number))
.Name = file_name & Format(Date, "yyyymmdd") & "_" & Format(Time, "Hh")
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "~"
.TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 9, 2, 9, 2, 2, 2, 2)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Next rep1
ws1.Activate
lastrow = Cells(ws1.Rows.Count, "A").End(xlUp).Row
Cells.Replace What:="true", Replacement:="TRUE", LookAt:=xlPart, _
searchorder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Cells.Replace What:="false", Replacement:="FALSE", LookAt:=xlPart, _
searchorder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
ws1.Columns("A:AZ").EntireColumn.AutoFit
ws2.UsedRange.ClearContents
ws2.Range("A1:G" & lastrow).Value = ActiveSheet.Range(Cells(1, 1), Cells(lastrow, 7)).Value
ws2.Range("N1:O" & lastrow).Value = ActiveSheet.Range(Cells(1, 8), Cells(lastrow, 9)).Value
ws2.Range("Y1:Y" & lastrow).Value = ActiveSheet.Range(Cells(1, 11), Cells(lastrow, 11)).Value
Your best bet would be to open the text file with something like an file system object, then replace() the character(s) you need, then write back to a temporary file and use that as an input. All of these steps are easily googleable, but if you get stuck, reply to this and I'll edit my post with more detail.

Sort by date in VBA

I have created a VBA function that selects data from an outside source and inserts it into an excel sheet. I want to be able to sort by the date with the most recent date appearing first in the list. I am not sure how to add this function (or what function to add) to my already existing function so it continues through the loops.
Sub getDividends()
Dim QuerySheet As Worksheet
Dim DataSheet As Worksheet
Dim EndDate As Date
Dim StartDate As Date
Dim Symbol As String
Dim qurl As String
Dim nQuery As Name
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Set DataSheet = ActiveSheet
StartDate = DataSheet.Range("B2").Value
EndDate = DataSheet.Range("B3").Value
Symbol = DataSheet.Range("B4").Value
Range("C7").CurrentRegion.ClearContents
'construct the URL for the query
qurl = "http://ichart.finance.yahoo.com/table.csv?s=" & Symbol
qurl = qurl & "&a=" & Month(StartDate) & "&b=" & Day(StartDate) & _
"&c=" & Year(StartDate) & "&d=" & Month(EndDate) - 1 & "&e=" & _
Day(EndDate) & "&f=" & Year(EndDate) & "&g=v&ignore=.csv"
Range("e1") = qurl
QueryQuote:
With ActiveSheet.QueryTables.Add(Connection:="URL;" & qurl, Destination:=DataSheet.Range("C7"))
.BackgroundQuery = True
.TablesOnlyFromHTML = False
.Refresh BackgroundQuery:=False
.SaveData = True
End With
Range("C7").CurrentRegion.TextToColumns Destination:=Range("C7"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, other:=False
Range(Range("C7"), Range("C7").End(xlDown)).NumberFormat = "mmm d, yyyy"
Range(Range("D7"), Range("G7").End(xlDown)).NumberFormat = "$0.00"
With ThisWorkbook
For Each nQuery In Names
If IsNumeric(Right(nQuery.Name, 1)) Then
nQuery.Delete
End If
Next nQuery
End With
'turn calculation back on
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
Range("C8:D500").Select
Selection.Sort Key1:=Range("C8"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
Range("C1").Select
Selection.ColumnWidth = 17.7
getPrice
Range("B4").Select
End Sub
Sub getPrice()
Dim QuerySheet As Worksheet
Dim DataSheet As Worksheet
Dim qurl As String
Dim i As Integer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Set DataSheet = ActiveSheet
Range("A7").CurrentRegion.ClearContents
qurl = "http://download.finance.yahoo.com/d/quotes.csv?s=" + Range("B4") + "&f=l1"
QueryQuote:
With ActiveSheet.QueryTables.Add(Connection:="URL;" & qurl, Destination:=DataSheet.Range("A7"))
.BackgroundQuery = True
.TablesOnlyFromHTML = False
.Refresh BackgroundQuery:=False
.SaveData = True
End With
Range("A7").CurrentRegion.TextToColumns Destination:=Range("A7"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, other:=False
'turn calculation back on
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
Range("A1").Select
Selection.ColumnWidth = 20
End Sub
Sub getaLL()
Dim i As Integer, j As Integer, n As Integer
n = Range("E3")
j = 9
Range("I2").CurrentRegion.ClearContents
Range("A5") = "Retrieving Dividends ..."
For i = 1 To n
Range("B4") = Cells(1 + i, 7)
getDividends
Cells(1, j) = Range("C5")
Range("C7:D500").Select
Selection.Copy
Cells(2, j).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Selection.ColumnWidth = 12
j = j + 2
Next i
Range("A5").Select
Selection.ClearContents
End Sub

Need to retain text format in code to import all csv files in folder

I'm trying to import all csv files in a folder into new worksheets in an Excel file while retaining the text format.
I pieced together some code through some research and have it nearly working the way I need, but when I run the macro, all of the columns are set to General.
Any insight into this is greatly appreciated.
Sub ImportCSV()
Application.ScreenUpdating = False
Const conSpath As String = "C:\MyPath\"
Dim sMasterFile As String
Dim sSheetName As String
Dim sFile As String
Dim iNextSheet As Integer
ChDir conSpath
sMasterFile = ActiveWorkbook.Name
iNextSheet = Sheets.Count
sFile = Dir(conSpath & "*.csv", vbNormal)
While sFile <> ""
Workbooks.OpenText Filename:=sFile, _
Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlTextQualifierDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, _
Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 2), _
Array(2, 2), Array(3, 2), Array(4, 2), Array(5, 2)), TrailingMinusNumbers:=True
sSheetName = ActiveSheet.Name
Sheets(sSheetName).Copy After:=Workbooks(sMasterFile).Sheets(iNextSheet)
Workbooks(sFile).Close SaveChanges:=False
iNextSheet = iNextSheet + 1
sFile = Dir
Wend
Application.ScreenUpdating = True
End Sub
Edit: I was able to change the columns to text, but I am still losing my leading zeros.
Sub ImportCSV()
Application.ScreenUpdating = False
Const conSpath As String = "C:\MyPath\"
Dim sMasterFile As String
Dim sSheetName As String
Dim sFile As String
Dim iNextSheet As Integer
ChDir conSpath
sMasterFile = ActiveWorkbook.Name
iNextSheet = Sheets.count
sFile = Dir(conSpath & "*.csv", vbNormal)
While sFile <> ""
Workbooks.OpenText FileName:=sFile, _
Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlTextQualifierDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, _
FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 2), _
Array(5, 2)), TrailingMinusNumbers:=True
sSheetName = ActiveSheet.Name: Sheets(sSheetName).Cells.NumberFormat = "#"
Sheets(sSheetName).Copy After:=Workbooks(sMasterFile).Sheets(iNextSheet)
Workbooks(sFile).Close True
iNextSheet = iNextSheet + 1
sFile = Dir
Wend
Application.ScreenUpdating = True
End Sub
The WorksheetFunction.Text method might solve your problem with leading zeros. This allows you to set the format on a single number that you want formatted as text.
If your numbers (including leading zeros) are all the same length, you could do something like this with the range of cells containing the numeric value:
Sub ConvertToTextWithLeadingZeros()
Dim rngText As Range
Set rngText = Selection
Dim rngCell As Range
Dim strText As String
For Each rngCell In rngText
strText = WorksheetFunction.Text(rngCell, "000000")
rngCell.NumberFormat = "#"
rngCell.value = strText
Next rngCell
End Sub
Just set "0000000" to contain a number of zeros equal to the number of digits you want (including leading zeros).
I solved the "losing-leading-zeros"-Problem handling csv-files with VBA this way:
With ThisWorkbook.Worksheets("tmp").QueryTables.Add(Connection:="TEXT;" & xFile, Destination:=Range("$A$1"))
.Name = Filename
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
The important part is the Attribute .TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
Every text-column needs a "2".

Yahoo query does not work

I have created an excel that using a vba code access yahoo web site to fetch stocks data.
The excel works fine most of the time but sometimes (and I can't find a rule/ motivation) it does not get the data from yahoo.
The strange thing is that if I do it step by step using the debugger it works but if I start the macro it does not work and am not able to fetch the data.
Do you have any idea?
Thanks,
Giancarlo
Below the subs I use t retrieve the data ...
Sub StrongestSmallCaps()
Dim frequency As String
Dim numRows As Integer
Dim LastRow As Integer
Dim stockTicker As String
Dim IndR As Integer
Dim Simbolo As String
Dim rsi As String
Dim ShortInter As Boolean
Dim NonIncr As Boolean
Worksheets("GreenLine").Select
LastRow = ActiveSheet.Cells(Rows.Count, "h").End(xlUp).Row
frequency = "d"
'Cancella contenuti celle stocastici
Range("j2:k70").Clear
Range("j2:k70").Select
Selection.Style = "Stocastic"
Range("i2:i70").Clear
Range("i2:i70").Select
Selection.Style = "Tick"
Application.Wait Now + TimeValue("00:00:03")
IndR = 2
'Loop through all tickers
For Ticker = 2 To LastRow
'Application.Wait Now + TimeValue("00:00:03")
stockTicker = Worksheets("GreenLine").Range("$h$" & Ticker)
If stockTicker = "" Then
GoTo NextIteration
End If
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = stockTicker
Cells(1, 1) = "Stock Quotes for " & stockTicker
Call DownloadStockQuotes(stockTicker, Worksheets("GreenLine").Range("$b$500"), Worksheets("GreenLine").Range("$b$600"), "$a$2", frequency)
'Application.Wait Now + TimeValue("00:00:03")
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, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1))
Sheets(stockTicker).Columns("A:G").ColumnWidth = 10
LastRow = Sheets(stockTicker).UsedRange.Row - 2 + Sheets(stockTicker).UsedRange.Rows.Count
If LastRow < 3 Then
Application.DisplayAlerts = False
Sheets(stockTicker).delete
GoTo NextIteration
Application.DisplayAlerts = True
End If
Rows("1:1").Select
Selection.delete Shift:=xlUp
Columns("B:B").Select
Selection.delete Shift:=xlToLeft
Columns("E:E").Select
Selection.delete Shift:=xlToLeft
Columns("E:E").Select
Selection.delete Shift:=xlToLeft
Rows("2:2").Select
Selection.INSERT Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
'CALCOLA STOCHASTIC
Worksheets("GreenLine").Select
Range("Cb100:Cm122").Select
Selection.Copy
Worksheets("GreenLine").Select
Sheets(stockTicker).Select
Range("e1").Select
ActiveSheet.Paste
If Cells(3, 8) < 20 Then
Worksheets("GreenLine").Select
Cells(IndR, 9) = stockTicker
Cells(IndR, 10) = "BUY"
Cells(IndR, 10).Select
Selection.Style = "Oversold"
Application.DisplayAlerts = False
Sheets(stockTicker).delete
Application.DisplayAlerts = True
'CALCOLA RSI
'Sheets(stockTicker).Select
'If Cells(3, 16) < 20 Then
' rsi = Cells(3, 16)
' Worksheets("GreenLine").Select
'
' Cells(IndR, 9) = stockTicker
' Cells(IndR, 11) = "OVS"
' Cells(IndR, 11).Select
' Selection.Style = "Oversold"
' Selection.Style = "Comma"
' IndR = IndR + 1
' Application.DisplayAlerts = False
' Sheets(stockTicker).delete
' Application.DisplayAlerts = True
'Else
' IndR = IndR + 1
' Application.DisplayAlerts = False
' Sheets(stockTicker).delete
' Application.DisplayAlerts = True
'End If
Else
Application.DisplayAlerts = False
Sheets(stockTicker).delete
Application.DisplayAlerts = True
'Sheets(stockTicker).Select
'If Cells(3, 16) < 20 Then
' rsi = Cells(3, 16)
' Worksheets("GreenLine").Select
'
' Cells(IndR, 9) = stockTicker
' Cells(IndR, 11) = "OVS"
' Cells(IndR, 11).Select
' Selection.Style = "Oversold"
' Selection.Style = "Comma"
'
' IndR = IndR + 1
' Application.DisplayAlerts = False
' Sheets(stockTicker).delete
' Application.DisplayAlerts = True
'Else
' Application.DisplayAlerts = False
' Sheets(stockTicker).delete
' Application.DisplayAlerts = True
'End If
End If
NextIteration:
Next Ticker
ErrorHandler:
Worksheets("GreenLine").Select
Application.ScreenUpdating = True
Range("h2:h70").Clear
Range("h2:h70").Select
Selection.Style = "Normal"
E
nd Sub
Sub DownloadStockQuotes(ByVal stockTicker As String, ByVal startDate As Date, ByVal endDate As Date, ByVal DestinationCell As String, ByVal freq As String)
Dim qurl As String
Dim StartMonth, StartDay, StartYear, EndMonth, EndDay, EndYear As String
StartMonth = Format(Month(Date) - 8, "00")
StartDay = Format(Day(Date), "00")
StartYear = Format(Year(Date), "00")
EndMonth = Format(Month(Date) - 1, "00")
EndDay = Format(Day(Date), "00")
EndYear = Format(Year(Date), "00")
Application.Wait Now + TimeValue("00:00:03")
qurl = "URL;http://table.finance.yahoo.com/table.csv?s=" + stockTicker + "&a=" + StartMonth + "&b=" + StartDay + "&c=" + StartYear + "&d=" + EndMonth + "&e=" + EndDay + "&f=" + EndYear + "&g=" + freq + "&ignore=.csv"
Application.Wait Now + TimeValue("00:00:03")
On Error GoTo ErrorHandler:
With ActiveSheet.QueryTables.Add(Connection:=qurl, Destination:=Range(DestinationCell))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "20"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
ErrorHandler:
End Sub
What I do is I issue this command first
On Error Resume Next ' this should get past 1004 errors but No Data will show in my error column
Then after I fetch the data, I check to see if there is really any data there and if not, I run the query again.
For some unknown reason it randomly fails and almost always works the second time.
But I hope you already solved your problem since it was posted so long ago.