Yahoo query does not work - vb.net

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.

Related

Hyperlink with spaces

I have a worksheets for my projects.
the first sheet is the main one the containing all the name of the projects.
the author sheets are for every project.
in the main sheet the name of the project has hyperlink to his sheet.
when running the code I got a pop msgbox that I write the new project name (look for "project_name").
the code does stuff.
but near the end there is the hyperlink code. (look for ActiveSheet.Hyperlinks.Add....)
so my problem is:
when I choose a project name like "abcd" everything works ok. But when I choose name like "ab cd". the code runs but the hyperlink doesn't work.
I realized that having a space in the project name makes the code not work.
thanks for the help.
p.s.
The notes are in Hebrew.
Sub New_project()
'--------------------------------------------------------------------------------------------------תחילת ריצת קוד
Dim Start, Finish, TotalTime As Date
Start = Timer
'--------------------------------------------------------------------------------------------------ביטול חישובים ועדכוני מסך והתראות
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
'--------------------------------------------------------------------------------------------------החזרת חישובים ועדכוני מסך והתראות
'Application.Calculation = xlCalculationAutomatic
'Application.ScreenUpdating = True
'Application.DisplayAlerts = True
'Application.AskToUpdateLinks = True
'--------------------------------------------------------------------------------------------------פתיחת חלונית והקלדת שם הפרויקט
'--------------------------------------------------------------------------------------------------אם לחצו cancel אז יציאה מהקוד
Dim project_name As String
project_name = InputBox("נא להקליד את שם הפרויקט החדש")
If Len(project_name) < 1 Then
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
MsgBox ("יציאה מהקוד")
Exit Sub
End If
'--------------------------------------------------------------------------------------------------בדיקה האם שם הגיליון לפרויקט החדש כבר קיים
Dim curSheet As Worksheet
Dim ArraySheets() As String
Dim x As Variant
Dim sheet_existing As Integer
x = 0
sheet_existing = 0
For Each curSheet In ActiveWorkbook.Worksheets
If curSheet.Name Like project_name Then
Worksheets(project_name).Activate
sheet_existing = 1
Finish = Timer
TotalTime = Format((Finish - Start) / 86400, "hh:mm:ss")
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
MsgBox ("שם הפרויקט כבר קיים" & vbNewLine & "זמן ריצת קוד: " & TotalTime)
Exit Sub
End If
Next curSheet
'iComp = StrComp(str1, str2, vbBinaryCompare)
'--------------------------------------------------------------------------------------------------הוספת גיליון חדש בסוף הקובץ
If sheet_existing = 0 Then
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = project_name
End If
'--------------------------------------------------------------------------------------------------הוספת כותרות
Range("A1") = "#"
Range("B1") = "תאריך"
Range("C1") = "שלב"
Range("D1") = "איש קשר"
Range("E1") = "הערות"
Range("F1") = "מסמכים"
Range("G1") = "ימים"
Range("H1") = "צבירה"
'--------------------------------------------------------------------------------------------------רוחב עמודה
Columns("A").ColumnWidth = 9
Columns("B").ColumnWidth = 11
Columns("C").ColumnWidth = 30
Columns("D").ColumnWidth = 16
Columns("E").ColumnWidth = 17
Columns("F").ColumnWidth = 9
Columns("G").ColumnWidth = 6
Columns("H").ColumnWidth = 10
'--------------------------------------------------------------------------------------------------הוספת מסגרת לתאים
Dim rng1 As Range
Set rng1 = Range(Cells(1, 1), Cells(27, 8))
With rng1.Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
Range("A:H").HorizontalAlignment = xlCenter
Range("A:H").VerticalAlignment = xlCenter
Rows(1).Font.Bold = True
Columns(1).Font.Bold = True
Range("A1:H1").Interior.Color = RGB(0, 176, 240)
Range("A2") = 1
Range("B2") = Date
'Range("C2") = "רשום כאן את השלב הראשון"
Range("G2") = 0
Range("H2") = 0
Range("N1:Q1").Merge
Range("N2:Q12").Merge
Range("N1:Q1").Interior.Color = RGB(0, 176, 240)
Range("N1:Q1") = "הערות"
'--------------------------------------------------------------------------------------------------הוספת מסגרת לתאים
Dim rng2 As Range
Set rng2 = Range(Cells(1, 14), Cells(12, 17))
With rng2.Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
Range("N:Q").HorizontalAlignment = xlCenter
Range("N:Q").VerticalAlignment = xlCenter
'--------------------------------------------------------------------------------------------------ספירת גיליונות בקובץ
Dim SheetCountA As Integer
SheetCountA = Application.Sheets.Count
'--------------------------------------------------------------------------------------------------העתקת כפתור חזרה לגיליון החדש
Sheets(SheetCountA - 1).Select
ActiveSheet.Shapes.Range(Array("Rectangle 1")).Select
Selection.Copy
Sheets(SheetCountA).Select
ActiveSheet.Paste Destination:=Worksheets(SheetCountA).Range("K1")
Sheets(SheetCountA - 1).Select
Range("B1").Copy
Sheets(SheetCountA).Select
Range("B1").PasteSpecial Paste:=xlPasteFormats
Application.CutCopyMode = False
Range("A1").Select
Sheets(SheetCountA - 1).Select
Range("A1").Select
Sheets("סיכום").Select
Dim LastRowA As Integer
LastRowA = Application.CountA(Range("B:B"))
'--------------------------------------------------------------------------------------------------הוספת מספור לפרויקט החדש
Cells(LastRowA + 1, 1) = Cells(LastRowA, 1) + 1
'--------------------------------------------------------------------------------------------------הוספת היפר-לינק
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:= _
project_name & "!A1", TextToDisplay:=project_name
Cells(LastRowA + 1, 2).HorizontalAlignment = xlCenter
Cells(LastRowA + 1, 2).VerticalAlignment = xlCenter
Range("A1").Select
'--------------------------------------------------------------------------------------------------זמן סיום ריצת קוד וחישוב
Finish = Timer
TotalTime = Format((Finish - Start) / 86400, "hh:mm:ss")
MsgBox ("הדו''ח מוכן" & vbNewLine & "זמן ריצת קוד: " & TotalTime)
'--------------------------------------------------------------------------------------------------שאלה האם לעבור לקוד שמרענן את הקובץ
Dim answer2 As Integer
answer2 = MsgBox("?האם לרענן את הקובץ", vbYesNo + vbQuestion, "מעבר לקוד הבא")
If answer2 = vbYes Then
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Call Refresh_file
End If
'--------------------------------------------------------------------------------------------------שמירת הקובץ
ThisWorkbook.Save
'--------------------------------------------------------------------------------------------------החזרת חישובים ועדכוני מסך והתראות
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
End Sub
To make the hyperlink valid, you just need to wrap the sheet name in quotes, so:
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:= _
project_name & "!A1", TextToDisplay:=project_name
becomes
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:="'" & _
project_name & "'" & "!A1", TextToDisplay:=project_name

Excel VBA - Save changes to "Book16" error

I have some data in my excel file and based on that data I'm using a macro for generating the report which should be saved in the place specified by path provided by the user. On my laptop, with Win10 everything is working fine, but on PC there is an error when we try to generate a report. Instead of saving the report in provided place excel is asking me to save data in "Book16" as shows the screenshot below. Do I have no idea why?
Here is the code of macro responsible for creating the report:
Sub Nationalreports()
Dim sh1 As Worksheet, N As Long
Dim st As String
Dim wbUnSaved As Workbook
Dim wbSaved As Workbook
Dim RedemptiontypeIncHdgs As Range
Dim RedemptiontypeExcHdgs As Range
Dim Fr As Long, LR As Long
Dim vaFiles As Variant
Dim i As Long
Dim wbkToCopy As Workbook
Dim ws As Worksheet, strFile As String
Dim File_path As String
Dim qry As QueryTable
Dim FilNams As Variant
Dim FilNamCntr As Long
Dim strQryName As String
Dim lastrow As Long
Application.ScreenUpdating = False
If Range("E8").Value = 0 Then
MsgBox "Please Specify FilePath", vbExclamation, "Please Specify
FilePath"
Range("E8").Activate
Exit Sub
End If
File_path = Sheets("Control").Range("E8").Value
Set wbksaved = ActiveWorkbook
MsgBox "Please Select MVRT Reports", vbInformation, "Select Files"
FilNams = Application.GetOpenFilename(FileFilter:="CSV Files
(*.csv),*.csv", _
Title:="Select Textfile to
Import", _
MultiSelect:=True)
If TypeName(FilNams) = "Boolean" Then
MsgBox "No Files Selected", vbExclamation, "No Files Selected"
Exit Sub
Else
End If
For FilNamCntr = LBound(FilNams) To UBound(FilNams)
FilNams(FilNamCntr) = "TEXT;" & FilNams(FilNamCntr)
Next FilNamCntr
For FilNamCntr = LBound(FilNams) To UBound(FilNams)
Sheets("Data").Cells.NumberFormat = "#"
Set wbkToCopy = Workbooks.Add
With ActiveSheet
If .Range("A" & Rows.Count).End(xlUp).Row = 1 Then
lastrow = 1
Else
lastrow = .Range("A" & Rows.Count).End(xlUp).Row + 1
End If
Set qry = .QueryTables.Add(Connection:=FilNams(FilNamCntr), _
Destination:=.Range("A" & lastrow))
With qry
.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 = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.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
End With
'-------------------------------------------------------------------------------------------
'NEW CODE:
'-------------------------------------------------------------------------------------------
'progress
'Rows("1:1").Delete
'ActiveSheet.UsedRange.Columns("A:T").SpecialCells(xlCellTypeVisible).Copy
'wbksaved.Sheets("Data").Cells(Rows.Count, "A").End(xlUp).Offset(0).PasteSpecial Paste:=xlPasteValues
ActiveSheet.UsedRange.Columns("A:T").SpecialCells(xlCellTypeVisible).Select
Selection.Copy
'wbksaved.Sheets("Data").Activate
'Range("A1").Select
'ActiveSheet.Paste
wbksaved.Sheets("Data").Paste
'ERROR IS HERE ^^^^^^^^^^^^^
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
Application.DisplayAlerts = False
ActiveWorkbook.Close False
Application.DisplayAlerts = True
Next FilNamCntr
Set wbkToCopy = Workbooks.Add
wbkToCopy.Sheets(1).Name = "Duplicates,Invalid"
wbkToCopy.Worksheets.Add().Name = "Breakdown"
wbkToCopy.Worksheets.Add().Name = "Summary"
wbksaved.Sheets("Redemption").UsedRange.Columns("C:D").Copy
Sheets("Duplicates,Invalid").Range("A1").PasteSpecial Paste:=xlPasteValues
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
' Duplicates & Invalids Sheet
Sheets("Duplicates,Invalid").Activate
Columns("B").Cut Destination:=Columns("F")
Columns("A").Cut Destination:=Columns("B")
Range("B1").Value = "Duplicate Codes"
Range("F1").Value = "Invalid Codes"
Range("A2").Value = "1"
Range("A3").Value = "2"
On Error Resume Next
Cells(2, 1).AutoFill Destination:=Range("A2:A" & Range("B" & Rows.Count).End(xlUp).Row), Type:=xlFillSeries
Range("E2").Value = "1"
Range("E3").Value = "2"
On Error Resume Next
Cells(2, 5).AutoFill Destination:=Range("E2:E" & Range("F" & Rows.Count).End(xlUp).Row), Type:=xlFillSeries
Range("A1").Value = "Nr."
Range("E1").Value = "Nr."
Columns("A:F").EntireColumn.AutoFit
Columns("A:F").HorizontalAlignment = xlCenter
Cells.Interior.Pattern = xlSolid
Cells.Interior.TintAndShade = -0.0499893185216834
Range("A1:B1,E1:F1").Interior.ThemeColor = xlThemeColorLight1
Range("A:B,E:F").Borders.LineStyle = xlContinuous
Range("A1:B1,E1:F1").Font.ThemeColor = xlThemeColorDark1
Range("A1:B1,E1:F1").Font.Bold = True
Application.Goto Reference:=Range("A1"), Scroll:=True
' Breakdown Sheet
Sheets("Breakdown").Activate
Cells.NumberFormat = "#"
wbksaved.Sheets("MVRT").UsedRange.Columns("A:D").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "A").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("F:F").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "E").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("H:H").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "F").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("N:N").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "G").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("S:S").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "H").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("K:K").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "I").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("J:J").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "J").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("M:M").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "K").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("Q:Q").SpecialCells(xlCellTypeVisible).Copy
ActiveSheet.Paste Destination:=Worksheets("Breakdown").Range("L:L")
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
'Range("O:P").Delete
Range("A1").Value = "UUID"
Range("B1").Value = "Security Code"
Range("C1").Value = "Customer Code"
Range("D1").Value = "Country Code"
Range("E1").Value = "Salesforce Id"
Range("F1").Value = "Merchant Name"
Range("G1").Value = "Unit Status"
Range("H1").Value = "Redemption Status"
Range("I1").Value = "Expires At"
Range("J1").Value = "Expired"
Range("K1").Value = "Suspended"
Range("L1").Value = "Redemption Date"
'Range("M:M").Replace What:="Invalid Rights", Replacement:="Other Country"
Range("B:L").Sort Key1:=Range("I:I"), Order1:=xlAscending, Header:=xlYes
Range("A:L").EntireColumn.AutoFit
Range("A1:L1").HorizontalAlignment = xlCenter
Cells.Interior.Pattern = xlSolid
Cells.Interior.TintAndShade = -0.0499893185216834
Range("A1:L1").Interior.ThemeColor = xlThemeColorLight1
Range("A:L").Borders.LineStyle = xlContinuous
Range("A1:L1").Font.ThemeColor = xlThemeColorDark1
Rows("1:1").Font.Bold = True
Application.Goto Reference:=Range("A1"), Scroll:=True
'Summary Sheet
Sheets("Summary").Activate
Range("C9").Value = "Country"
Range("C10").Value = "Merchant Name"
Range("C11").Value = "Type"
Range("C16").Value = "Redemption Type"
Range("C17").Value = "Invalid"
Range("C18").Value = "Duplicates"
Range("C19").Value = "Suspended"
Range("C20").Value = "Voucher Expired"
Range("C21").Value = "Payment Invalid"
Range("C22").Value = "Payment Refunded"
Range("C23").Value = "Redeemed"
Range("C24").Value = "Total Codes Sent In"
Range("D9").FormulaR1C1 = "=Breakdown!R[-7]C[0]"
Range("D10").FormulaR1C1 = "=Breakdown!R[-8]C[2]"
Range("D11").FormulaR1C1 = "Offsite Redemptions"
Range("D16").FormulaR1C1 = "No."
Range("D17").FormulaR1C1 = "=COUNTA('Duplicates,Invalid'!C[2])-1"
Range("D18").FormulaR1C1 = "=COUNTA('Duplicates,Invalid'!C[-2])-1"
Range("D19").Formula = "=COUNTIFS(Breakdown!K:K,""*true*"",Breakdown!H:H,""*Forced redeemable*"")"
'Range("D19").AutoFill Destination:=Range("D19:D25"), Type:=xlFillCopy
Range("D20").Formula = "=COUNTIFS(Breakdown!J:J,""*true*"",Breakdown!K:K,""*false*"",Breakdown!G:G,""*collected*"",Breakdown!H:H,""*Forced redeemable*"")"
'payment not received:
Range("D21").Formula = "=COUNTIFS(Breakdown!K:K,""*false*"",Breakdown!G:G,""*resigned*"",Breakdown!H:H,""*Forced redeemable*"") + COUNTIFS(Breakdown!K:K,""*false*"",Breakdown!G:G,""*pending*"",Breakdown!H:H,""*Forced redeemable*"")"
'payment refunded:
Range("D22").Formula = "=COUNTIFS(Breakdown!G:G,""*deleted*"",Breakdown!K:K,""*false*"",Breakdown!H:H,""*Forced redeemable*"")"
Range("D23").Formula = "=COUNTIF(Breakdown!H:H,""*redeemed*"")"
'sum-formula:
Range("D24").Formula = "=COUNTA(Breakdown!A:A)-1 + SUM(D17:D18)"
Range("C:D").Copy
Range("C:C").PasteSpecial xlPasteValues
Application.CutCopyMode = False
Range("A:B,E:F").ColumnWidth = 26
Range("C:D").ColumnWidth = 63.29
Range("C:D").HorizontalAlignment = xlCenter
Cells.Interior.Pattern = xlSolid
Cells.Interior.TintAndShade = -0.0499893185216834
Range("C1:D5,C9:C11,C16:D16,C24:D24").Interior.ThemeColor =
xlThemeColorLight1
Range("D9:D11,C16:D24").Borders.LineStyle = xlContinuous
Range("C9:C11,C16:D16,C24:D24").Font.ThemeColor = xlThemeColorDark1
Range("C9:D11,C16:D24").Font.Bold = True
Range("C3:D3").Merge True
Dim myR As Range
Set myR = Range("C3:D3")
wbksaved.Sheets("Control").Shapes("Groupon Logo").Copy
Range("C3:D3").PasteSpecial xlPasteFormats
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
Selection.ShapeRange.ScaleWidth 1, msoFalse, msoScaleFromTopLeft
Selection.ShapeRange.ScaleHeight 1, msoFalse, msoScaleFromTopLeft
Selection.ShapeRange.IncrementLeft (myR.Width - Selection.ShapeRange.Width) / 2
Application.Goto Reference:=Range("A1"), Scroll:=True
Country = Range("D9").Value
'Merchant_ID = Range("D10").Value This was DELETED on Lorene request
Merchant_Name = Range("D10").Value
dt = Format(CStr(Now), "dd_mm_yyyy_hh_mm_ss")
File_Name = File_path & "\" & "Report" & " " & Merchant_Name & " " &
Merchant_ID & " " & dt & ".xlsx"
ActiveWorkbook.SaveAs Filename:=File_Name, FileFormat:=51
ActiveWorkbook.Close
Application.DisplayAlerts = False
Sheets("Data").Cells.Delete
Application.DisplayAlerts = True
Sheets("Control").Select
MsgBox "Report Created", vbInformation, "Report Created"
Application.ScreenUpdating = True
End Sub
Can you try instead of this:
ActiveSheet.UsedRange.Columns("A:T").SpecialCells(xlCellTypeVisible).Select
Selection.Copy
wbksaved.Sheets("Data").Paste
To write this:
ActiveSheet.Columns("A:T").SpecialCells(xlCellTypeVisible).Copy
wbksaved.Sheets("Data").Range("A1").Paste
And to see whether the "error" would still exist? In general, Selection.Copy and ActiveSheet, ActiveCell should be avoided whenever possible - How to avoid using Select in Excel VBA

Loop code to run macro multiple times

I have this vba macro that extracts data from a text file and puts it into a column in Excel. The files are named by days (2016mmdd). Currently, I run this macro for each day. Now I want it such that when this Macro is run, the data for all the days in the declared month (say August) will be automatically extracted into different columns (a column per each day of the month). So that I won't have to manually run it 31 times if there are 31 days in the month. Thanks for helping.
Sub Macro7()
'
' Macro7 Macro
'
' Keyboard Shortcut: Ctrl+x
'
Dim fileDate, rng, rng1, rng2, rng3, rcell As String
b = InputBox("Enter file Name mmdd", "File name")
rcell = InputBox("Enter cell reference", "Reference name")
rng = "$" & rcell & "$2"
rng1 = rcell & "2:" & rcell & "14"
rng2 = rcell & "52:" & rcell & "62"
rng3 = rcell & "2:" & rcell & "101"
Filename = "j:\files\2016" & b & "2259.txt"
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;j:\files2016" & b & "2259.txt", Destination:= _
Range(rng))
.Name = "tr" & b
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(9, 1, 9)
.TextFileFixedColumnWidths = Array(103, 4)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Range(rng1).Select
Selection.Delete Shift:=xlUp
ActiveWindow.SmallScroll Down:=45
Range(rng2).Select
Selection.Delete Shift:=xlUp
ActiveWindow.SmallScroll Down:=-60
Range(rng3).Select
End Sub
The quick approach would be to re-write Sub Macro7() to accept parameters, e.g.
Sub ImportFiles(FName As String, ColNum As Integer)
' blablabla
' work with range objects ... not with patched strings containing range addresses
Dim Rng As Range, Rng1 As Range, Rng2 As Range, Rng3 As Range
Set Rng = Cells(2, ColNum)
Set Rng1 = Range(Cells(2, ColNum), Cells(14, ColNum))
Set Rng2 = Range(Cells(52, ColNum), Cells(62, ColNum))
Set Rng3 = Range(Cells(2, ColNum), Cells(101, ColNum))
Filename = "j:\files\2016" & FName & "2259.txt"
' and replace <Destination := Range(Rng)> by <Destination := Rng>
' blablabla
' use the range objects defined/set earlier ... save on Select/Selection
Rng1.Delete xlUp
Rng2.Delete xlUp
Rng3.Select
End Sub
and have a calling Macro e.g.
Sub DoWorklist()
ImportFiles "0901", 1
ImportFiles "0902", 2
ImportFiles "0903", 3
' blablabla
'alternative
Dim Idx As Integer
For Idx = 1 To 30
' to overcome well spotted chr() issue we convert running number Idx
' into 2 digit string with leading "0"
ImportFiles "09" & Format(Idx, "00"), Idx
Next Idx
End Sub

VBA Stock info retrieval into Excel

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

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