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
Related
Hi I have the following VBA code and it fails at one place time and again.
Sub theathersplitmacro()
Dim SDrv As String
Dim DDrv As String
Dim Sfname As String
Dim Dfname As String
Dim wkbSrc As Workbook
Dim wkbDst As Workbook
Dim shtname(1 To 16) As Variant
Dim i As Integer
Dim Lastrow As Variant
Dim destination_file As String
'Dim regions As String
Dim theater As String
Dim j As Integer
For j = 2 To 9
destination_file = Workbooks("VBA Master
Copy.xlsb").Sheets("Data").Range("A" & j).Value & ".xlsb"
'regions = Workbooks("VBA Master Copy.xlsb").Sheets("Data").Range("C" &
j).Value
theater = Workbooks("VBA Master Copy.xlsb").Sheets("Data").Range("D" &
j).Value
shtname(1) = "DataQTR"
shtname(2) = "DataSWDriver"
shtname(3) = "DataMTD"
shtname(4) = "DataWeekly"
shtname(5) = "DataSoftware"
shtname(6) = "DataCloud"
shtname(7) = "DataServices"
shtname(8) = "TopCustomer"
shtname(9) = "TopDeals"
shtname(10) = "TopPartners"
shtname(11) = "DataForecast"
shtname(12) = "DataFcstCloud"
shtname(13) = "DataFcstSoftware"
shtname(14) = "DataFcstServices"
shtname(15) = "DataServicesSW"
shtname(16) = "TopCustomerDebooking"
SDrv = "C:\Users\skumawat\Documents\Explore\"
Sfname = "Theater_Bookings - New Format with formulae.xlsb"
DDrv = "C:\Users\skumawat\Documents\Explore\"
Dfname = destination_file
With Application
.EnableEvents = False
.ScreenUpdating = False
.DisplayAlerts = False
.Calculation = xlCalculationManual
End With
Set wkbSrc = Workbooks.Open(SDrv & Sfname)
Set wkbDst = Workbooks.Open(DDrv & Dfname)
For i = 1 To 15
wkbSrc.Worksheets(shtname(i)).Activate
Lastrow = wkbSrc.Worksheets(shtname(i)).Range("k" &
Rows.Count).End(xlUp).Row
wkbSrc.Worksheets(shtname(i)).Range("A1:BZ" & Lastrow).Select
If Worksheets(shtname(i)).AutoFilterMode = True Then
wkbSrc.Worksheets(shtname(i)).AutoFilter.Sort.SortFields.Clear
End If
wkbSrc.Worksheets(shtname(i)).Range("A1:BZ" & Lastrow).Select
Selection.AutoFilter
wkbSrc.Worksheets(shtname(i)).Range("$k$1:$k$" & Lastrow).AutoFilter
Field:=11, Criteria1:=theater
Range("$A$1:$BZ$" & Lastrow).SpecialCells(xlCellTypeVisible).Copy
wkbDst.Worksheets(shtname(i)).Range("A1").PasteSpecial
xlPasteValuesAndNumberFormats
Application.CutCopyMode = False
Next i
wkbDst.Worksheets("aMapping").Activate
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Workbooks("VBA Master Copy.xlsb").Sheets("Data").Activate
Range("G" & j).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
wkbDst.Worksheets("aMapping").Activate
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks
_
:=False, Transpose:=True
Application.CutCopyMode = False
With wkbDst
.Save
.Close
End With
Workbooks("VBA Master Copy.xlsb").Sheets("Data").Range("E" & j).Value =
"Completed"
Next j
With wkbSrc
.Close
End With
With Application
.EnableEvents = True
.ScreenUpdating = True
.DisplayAlerts = True
.Calculation = xlCalculationAutomatic
End With
Workbooks("VBA Master Copy.xlsb").Activate
End Sub
The error I get is in the following line
wkbSrc.Worksheets(shtname(i)).Range("$k$1:$k$" & Lastrow).AutoFilter
Field:=11, Criteria1:=theater
You use a wrong range. To set the autofilter user your range "A1:BZ" & lastrow again. If you use only $K you have no column 11 for your criteria.
The whole code is trying to get historical data from Yahoo Finance using VBA. Everything works pretty fine except the code whereby I try to get the company's name using from the Yahoo site.
This first piece of code is just to chceck that there are no mistakes in the definition in variables or whatever.
Enum READYSTATE
READYSTATE_UNINITIALIZED = 0
READYSTATE_LOADING = 1
READYSTATE_LOADED = 2
READYSTATE_INTERACTIVE = 3
READYSTATE_COMPLETE = 4
End Enum
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
Dim ohtml As HTMLText
On Error GoTo error_getdata
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Set datasheet = ActiveSheet
StartDate = datasheet.Range("startDate").Value
EndDate = datasheet.Range("endDate").Value
symbol = datasheet.Range("ticker").Value
symbol = UCase(symbol)
'Download data from Yahoo Finance'
Sheets("Home").Activate
Sheets(symbol).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(symbol).Range("a1") & "&q=q&y=0&z=" & _
symbol & "&x=.csv"
eurl = "https://finance.yahoo.com/quote/" & symbol & "?ltr=2"
Here is where the problem spots. I try to scrap the html of the site looking for the company's name. If I look at the html code of the website, I find that the company's name is labeled as reactid="239". I guess that what I have to do is to use getelementsbyID("239") but I am not sure about that.
'''''
Dim objIe As Object
Set objIe = CreateObject("InternetExplorer.Application")
objIe.Visible = False
objIe.navigate eurl
Application.StatusBar = "Looking for information in Yahoo Finance"
While (objIe.Busy Or objIe.READYSTATE <> 4): DoEvents: Wend
Set xobj = objIe.querySelectorAll("[reactid=239]")
Debug.Print xobj.innerText
Set xobj = Nothing
objIe.Quit
Set objIe = Nothing
Application.StatusBar = ""
'Sort the existence of a ticker in our sheet and create a new one '
Dim worksh As Integer
Dim worksheetexists As Boolean
Dim x As Integer
worksh = Application.Sheets.Count
worksheetexists = False
For x = 1 To worksh
If Worksheets(x).Name = symbol Then
worksheetexists = True
Sheets(symbol).Delete
ActiveWorkbook.Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = symbol
Exit For
End If
Next x
If worksheetexists = False Then
ActiveWorkbook.Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = symbol
End If
' Load data '
QueryQuote:
With Sheets(symbol).QueryTables.Add(Connection:="URL;" & qurl, Destination:=Sheets(symbol).Range("a1"))
.BackgroundQuery = True
.TablesOnlyFromHTML = False
.Refresh BackgroundQuery:=False
.SaveData = True
End With
Sheets(symbol).Range("a1").CurrentRegion.TextToColumns Destination:=Sheets(symbol).Range("a1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, other:=False
Sheets(symbol).Columns("A:G").ColumnWidth = 12
'Sort data'
LastRow = Sheets(symbol).UsedRange.Row - 2 + Sheets(symbol).UsedRange.Rows.Count
Sheets(symbol).Sort.SortFields.Add Key:=Range("A2"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With Sheets(symbol).Sort
.SetRange Range("A1:G" & LastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
.SortFields.Clear
End With
Exit Sub
error_getdata:
MsgBox ("Fatal error. Please insert a valid sticker for the stock")
End Sub
I heed that this could not be the most efficient way to get what I want. First I want to learn how to get it done and then I will take on the efficiency of the program.
Edit: Using some answers, I edited a bit the code, it still shows up an error (error 438) on the line:
Set xobj = objIe.querySelectorAll("[reactid=239]")
I'd look into using http://www.w3schools.com/jsref/met_document_queryselectorall.asp
which can allow selection of nodes using CSS selector syntax and there is a reference for this syntax at http://www.w3schools.com/cssref/css_selectors.asp
So perhaps something along the lines of
document.querySelectorAll("[reactid=239]")
Incidentally, you can browse the library if you use a Tools Reference to
Microsoft HTML Object Library
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.
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
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.