My code opens workbook, copies, and paste into this main workbook (essentially it consolidates several worksheets from different workbooks) but it crashes and excel closes and re-opens (recover). However when I add breakpoints it runs without issues. The source workbooks have similar layout / headers. It has formatting inside as well hence the copying of formats below. I have tried commenting out the formatting portion, commenting out the ContinueDo portion, and it still crashes. What did i do wrong? This is my code:
Private Sub CommandButton1_Click()
Dim File_Path As String, wsSrce As String
Dim File_Name As String
Dim firstrow, LastRow As Long
Dim wbDst As Workbook, wbSrce As Workbook, New_Workbook As Workbook
Dim wsDst As Worksheet
Dim rng As Range, r1 As Range, r2 As Range
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.DisplayAlerts = False
.EnableEvents = False
End With
wsSrce = "Part A"
Set wbDst = ThisWorkbook
Set wsDst = wbDst.Worksheets("Consolidated Data") 'destination sheet
wsDst.Range("A5:AI1048576").Clear
wsDst.Range("AM5:AQ1048576").Clear
wsDst.Range("AS5:BJ1048576").Clear
wsDst.Range("Aj5:al1048576").ClearFormats
wsDst.Range("Ar5:ar1048576").ClearFormats
File_Path = wbDst.Worksheets("Folder Reference").Cells(1, 2) & "\"
File_Name = Dir(File_Path & "*.xls*")
ActiveRow = 5
Do While File_Name <> ""
Set wbSrce = Workbooks.Open(Filename:=File_Path & File_Name, UpdateLinks:=False, Password:="MBIShariah")
For i = 1 To 5
If Left(Worksheets(i).Name, 6) = "Part A" Then
Worksheets(i).Activate
wsSrce_rename = Worksheets(i).Name
End If
Next i
firstrow = 1 + Application.WorksheetFunction.Match("No", Worksheets(wsSrce_rename).Columns("A:A"), 0)
LastRow = wbSrce.Worksheets(wsSrce_rename).Cells(Rows.Count, 8).End(xlUp).Row
If LastRow = 4 Then
GoTo ContinueDo
End If
wbSrce.Worksheets(wsSrce_rename).Range("A" & firstrow & ":AI" & LastRow).Copy
wsDst.Cells(ActiveRow, 1).PasteSpecial xlValues
wsDst.Cells(ActiveRow, 1).PasteSpecial xlFormats
wbSrce.Worksheets(wsSrce_rename).Range("AJ" & firstrow & ":AN" & LastRow).Copy
wsDst.Cells(ActiveRow, 39).PasteSpecial xlValues
wsDst.Cells(ActiveRow, 39).PasteSpecial xlFormats
wbSrce.Worksheets(wsSrce_rename).Range("AO" & firstrow & ":BJ" & LastRow).Copy
wsDst.Cells(ActiveRow, 45).PasteSpecial xlValues
wsDst.Cells(ActiveRow, 45).PasteSpecial xlFormats
LastRowDst = wsDst.Cells(Rows.Count, 8).End(xlUp).Row
Set r1 = wsDst.Range("AJ" & ActiveRow & ":AL" & LastRowDst)
Set r2 = wsDst.Range("AR" & ActiveRow & ":AR" & LastRowDst)
Set rng = Union(r1, r2)
With rng.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With rng.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With rng.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With rng.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With rng.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With rng.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
Application.CutCopyMode = False
ContinueDo:
ActiveRow = 1 + wsDst.Cells(1048576, 8).End(xlUp).Row
wbSrce.Close savechanges:=False
' Kill File_Path & File_Name
File_Name = Dir()
Loop
wsDst.Activate
wsDst.Cells(1, 1).Select
'ActiveWorkbook.RefreshAll
MsgBox "Data copied."
With Application
.ScreenUpdating = True
.Calculation = xlAutomatic
.DisplayAlerts = True
.EnableEvents = True
End With
End Sub
How to apply a macro function with three command buttons ? I tried with below code.. but returns the macro applied on different sheet.
cmd button1: browses the main raw data file.
cmd button2: vlookup data file for the main raw data file.
cmd button3: Run the macro below function on the main raw data file.
your ideas will be much helpful.. thanks in advance.
Option Explicit
Sub currentZOE3()
'declare variable to store path
Dim Get_Path As String
Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFilePicker)
'To allow or disable to multi select
fileExplorer.AllowMultiSelect = False
With fileExplorer
If .Show <> 0 Then
Get_Path = .SelectedItems(1)
End If
Worksheets("sheet1").Cells(3, 4).Value = Get_Path
End With
End Sub
Sub lastweekZOE3()
'declare variable to store path
Dim Get_Path As String
Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFilePicker)
'To allow or disable to multi select
fileExplorer.AllowMultiSelect = False
With fileExplorer
If .Show <> 0 Then
Get_Path = .SelectedItems(1)
End If
Worksheets("sheet1").Cells(5, 4).Value = Get_Path
End With
End Sub
Sub Macro4()
'
' Macro4 Macro
'
'
Dim updWb As Workbook
Dim DSheet As Worksheet
Set updWb = Workbooks.Open(Worksheets("sheet1").Cells(3, 4).Value)
Set DSheet = updWb.Sheets("Sheet1")
Cells.Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Font
.Name = "Calibri"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
End With
ActiveWindow.ScrollColumn = 2
ActiveWindow.ScrollColumn = 3
ActiveWindow.ScrollColumn = 4
ActiveWindow.ScrollColumn = 5
ActiveWindow.ScrollColumn = 6
ActiveWindow.ScrollColumn = 7
ActiveWindow.ScrollColumn = 8
ActiveWindow.ScrollColumn = 9
ActiveWindow.ScrollColumn = 10
ActiveWindow.ScrollColumn = 11
ActiveWindow.ScrollColumn = 12
ActiveWindow.ScrollColumn = 13
Columns("N:N").Select
Selection.TextToColumns Destination:=Range("N1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
'
ActiveWindow.ScrollColumn = 2
ActiveWindow.ScrollColumn = 3
ActiveWindow.ScrollColumn = 4
ActiveWindow.ScrollColumn = 5
ActiveWindow.ScrollColumn = 6
ActiveWindow.ScrollColumn = 7
ActiveWindow.ScrollColumn = 8
ActiveWindow.ScrollColumn = 9
ActiveWindow.ScrollColumn = 10
ActiveWindow.ScrollColumn = 11
ActiveWindow.ScrollColumn = 12
Columns("Q:S").Select
Selection.Insert Shift:=xlToRight
Range("Q1") = "Concantenate"
Range("R1") = "Delivery Plan"
Range("S1") = "Last Week Comments"
Range("Q2").Select
ActiveCell.FormulaR1C1 = "=RC[-16]&RC[-9]&RC[-7]"
Range("S2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-2],'[Last Week.xlsx]Sheet1'!C1:C2,2,0)"
Range("R2").Select
ActiveCell.FormulaR1C1 = _
"=IFS(RC22=""YBWR"",""What"",ISNUMBER(RC25),""Fully Delivered"",RC19=""Billable Only"",""BILLABLE ONLY"",AND(ISBLANK(RC25),NOT(ISBLANK(RC27))),""Under shipment"",AND(ISBLANK(RC25),ISBLANK(RC27),ISNUMBER(RC14)),""Under packing"",AND(ISBLANK(RC25),ISBLANK(RC27),ISBLANK(RC14)),TEXT(WEEKNUM(RC23),""W00""))"
Range("P3").Select
Selection.End(xlDown).Select
Range("Q8833:S8833").Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
Cells.Select
Range("Q8833").Activate
Selection.Columns.AutoFit
With Cells
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=($R1=""What"")"
With .FormatConditions(.FormatConditions.Count)
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 12173758
.TintAndShade = 0
End With
StopIfTrue = False
End With
End With
With Cells
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=($R1=""Fully Delivered"")"
With .FormatConditions(.FormatConditions.Count)
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 5691552
.TintAndShade = 0
End With
StopIfTrue = False
End With
End With
With Cells
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=($R1=""under shipment"")"
With .FormatConditions(.FormatConditions.Count)
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 3774674
.TintAndShade = 0
End With
StopIfTrue = False
End With
End With
With Cells
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=($R1=""under packing"")"
With .FormatConditions(.FormatConditions.Count)
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 15793920
.TintAndShade = 0
End With
StopIfTrue = False
End With
End With
Sheets(Array("Sheet2", "Sheet3")).Select
Sheets("Sheet3").Activate
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Range("A1").Select
Selection.AutoFilter
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Add2 Key:= _
Range("A1:A8837"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveSheet.Range("$A$1:$BE$8837").AutoFilter Field:=1
'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
Dim pvtfield As PivotField
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Sheet1")
'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="PivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="PivotTable")
'Insert Row Fields
With ActiveSheet.PivotTables("PivotTable").PivotFields("Sold to name")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Sales Document")
.Orientation = xlRowField
.Position = 2
End With
With ActiveSheet.PivotTables("PivotTable").PivotFields("Customer purchase order number")
.Orientation = xlRowField
.Position = 3
End With
'Insert Column Fields
With ActiveSheet.PivotTables("PivotTable").PivotFields("Delivery Plan")
.Orientation = xlColumnField
.Position = 1
End With
'Insert Data Field
With ActiveSheet.PivotTables("PivotTable").PivotFields("SO Net value")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.NumberFormat = "#,##0"
.Name = " Sum SO Net value "
End With
'classic and expand/collapse button removal
Range("C7").Select
With ActiveSheet.PivotTables("PivotTable")
.InGridDropZones = True
.RowAxisLayout xlTabularRow
End With
Range("B4").Select
ActiveSheet.PivotTables("PivotTable").ShowDrillIndicators = False
'Format Pivot
TableActiveSheet.PivotTables("PivotTable").ShowTableStyleRowStripes = TrueActiveSheet.PivotTables("PivotTable").TableStyle2 = "PivotStyleMedium9"
End Sub
Once you have the path of the file using the FileDialog method.
You can use the below function to open that excel and update the contents of it's worksheets.
Dim updWb As Workbook, wSheet As Worksheet
Set updWb = Workbooks.Open("<path of the workbook to be updated>")
Set wSheet = updWb.Sheets("<sheet-name> or <sheet-index>")
Summary: Find text/string based on list in another sheet and adjust trailing zeros with border around the range.
The excel workbook containing two sheet.
Sheet1 Name: List (having column A with text/string to be find and column B having numerical value) as in first image.
Sheet2 Name: "Raw" containing text anywhere and below numerical value with different decimal points. Also having few blank rows between set of range as in image 2.
I have recorded macro and tried to edit it. This macro working for Text1. Below macro find text1 in "raw" sheet and adjust the display of trailing zeros based on B1 value of list sheet.
How to loop the all listed text in column A of sheet list and adjust display of trailing zeros with outside borders. Output in image 3. Find as xlpart.
Sheet1 or list
Sheet2 or another sheet
Output
Sub Macro1()
Dim sFirstAddress As String
Dim rng As Excel.Range
With Sheets("Raw").Range("A1:DZ1000") '.UsedRange ???
'how to loop for list of text/string present in column A as in image 1.
Set C = .Find(What:="Text1", After:=ActiveCell, LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True, _
SearchFormat:=False)
If Not C Is Nothing Then
FirstAddress = C.Address
Do
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
ActiveCell.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
'how to loop for number in column B for adjusting/Keeping trailing zero's
If Sheets("List").Range("B1") = 1 Then
Selection.NumberFormat = "0.0"
Else
If Sheets("List").Range("B1") = 2 Then
Selection.NumberFormat = "0.00"
Else
If Sheets("List").Range("B1") = 3 Then
Selection.NumberFormat = "0.000"
End If
End If
End If
Selection.End(xlDown).Select
Cells.FindNext(After:=ActiveCell).Activate
Set C = .FindNext(C)
If C Is Nothing Then
GoTo DoneFinding
End If
Loop While C.Address <> FirstAddress
End If
DoneFinding:
End With
End Sub
By doing trial and error continuously for 6 hours, I am able to loop both columns of list sheet and output as expected. Below code working perfectly.
Dim FirstAddress As String
Dim MySearch As Variant
Dim myColor As Variant
Dim Rng As Range
Dim I As Long
Dim item As Range
For Each item In Sheets("List").UsedRange.Columns("A").Cells
MySearch = Array(item.Value2)
If item.Value2 = "" Then
Exit Sub
Else
With Sheets("Raw").UsedRange 'Range("B1:AA10000")
For I = LBound(MySearch) To UBound(MySearch)
Set Rng = .Find(What:=MySearch(I), After:=.Cells(.Cells.Count), _
LookIn:=xlValues, LookAt:=xlPart, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
If Not Rng Is Nothing Then
FirstAddress = Rng.Address
Do
With Rng.Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = 0
.TintAndShade = 0
End With
Rng.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
If item.Offset(, 1).Value2 = 1 Then
Selection.NumberFormat = "0.0"
Else
If item.Offset(, 1).Value2 = 2 Then
Selection.NumberFormat = "0.00"
Else
If item.Offset(, 1).Value2 = 3 Then
Selection.NumberFormat = "0.000"
Else
If item.Offset(, 1).Value2 = 4 Then
Selection.NumberFormat = "0.0000"
End If
End If
End If
End If
Selection.Borders(xlEdgeLeft).LineStyle = xlContinuous
Selection.Borders(xlEdgeRight).LineStyle = xlContinuous
Selection.Borders(xlEdgeBottom).LineStyle = xlContinuous
Selection.Borders(xlEdgeTop).LineStyle = xlContinuous
Set Rng = .FindNext(Rng)
Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
End If
Next I
End With
End If
Next
End Sub
Until today my Excel 2016 power query was able to obtain historical stock pricing data from the following URL https://finance.yahoo.com/quote/AAL/history?p=AAL. The Credential type was anonymous and the privacy level was public. I also tried using my username and password for my yahoo account in the Web Credential window with no luck. Excel returns a message that contains a 301 response.
Power query does work with Google Finance but the URL https://www.google.com/finance/historical?q=NASDAQ%3AAAL&ei=GqITWbGNIMvIebuQqXA has a parameter "ei" that makes no sense to me and I don't think I would be able to automate this.
Question; has yahoo recently changed so that this type of request is no longer viable?
Question; does anyone have VBA example of Yahoo Query Language (YQL) requesting historical stock quotes from yahoo.api?
Thanks for any help with this.
I think Yahoo changed it's API very recently. Download the file from the link titled "Get Excel Spreadsheet to Download Bulk Historical Stock Data from Google Finance"
http://investexcel.net/multiple-stock-quote-downloader-for-excel/
'Samir Khan
'simulationconsultant#gmail.com
'The latest version of this spreadsheet can be downloaded from http://investexcel.net/multiple-stock-quote-downloader-for-excel/
'Please link to http://investexcel.net if you like this spreadsheet
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
qurl = "http://finance.google.com/finance/historical?q=" & stockTicker
qurl = qurl & "&startdate=" & MonthName(Month(StartDate), True) & _
"+" & Day(StartDate) & "+" & Year(StartDate) & _
"&enddate=" & MonthName(Month(EndDate), True) & _
"+" & Day(EndDate) & "+" & Year(EndDate) & "&output=csv"
On Error GoTo ErrorHandler:
QueryQuote:
With ActiveSheet.QueryTables.Add(Connection:="URL;" & qurl, Destination:=Range(DestinationCell))
.BackgroundQuery = True
.TablesOnlyFromHTML = False
.Refresh BackgroundQuery:=False
.SaveData = True
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
Dim numStockErrors As Integer
Dim numStockSuccess As Integer
numStockErrors = 0
numStockSuccess = 0
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
lastErrorRow = ActiveSheet.Cells(Rows.Count, "J").End(xlUp).Row
lastSuccessRow = ActiveSheet.Cells(Rows.Count, "L").End(xlUp).Row
ClearErrorList lastErrorRow
ClearSuccessList lastSuccessRow
lastRow = ActiveSheet.Cells(Rows.Count, "a").End(xlUp).Row
frequency = Worksheets("Parameters").Range("b7")
'Delete all sheets apart from Parameters sheet
Dim ws As Worksheet
Application.DisplayAlerts = False
For Each ws In Worksheets
If ws.Name <> "Parameters" And ws.Name <> "About" Then ws.Delete
Next
Application.DisplayAlerts = True
'Loop through all tickers
For ticker = 12 To lastRow
stockTicker = Worksheets("Parameters").Range("$a$" & ticker)
If stockTicker = "" Then
GoTo NextIteration
End If
Sheets.Add After:=Sheets(Sheets.Count)
If InStr(stockTicker, ":") > 0 Then
ActiveSheet.Name = Replace(stockTicker, ":", "")
Else
ActiveSheet.Name = stockTicker
End If
Cells(1, 1) = "Stock Quotes for " & stockTicker
Call DownloadStockQuotes(stockTicker, Worksheets("Parameters").Range("$b$5"), Worksheets("Parameters").Range("$b$6"), "$a$2", frequency)
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))
If InStr(stockTicker, ":") > 0 Then
stockTicker = Replace(stockTicker, ":", "")
End If
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
numStockErrors = numStockErrors + 1
ErrorList stockTicker, numStockErrors
GoTo NextIteration
Application.DisplayAlerts = True
Else
numStockSuccess = numStockSuccess + 1
If Left(stockTicker, 1) = "^" Then
SuccessList Replace(stockTicker, "^", ""), numStockSuccess
Else
SuccessList stockTicker, numStockSuccess
End If
End If
Sheets(stockTicker).Sort.SortFields.Add Key:=Range("A3:A" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With Sheets(stockTicker).Sort
.SetRange Range("A2:G" & lastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("a3:a" & lastRow).NumberFormat = "yyyy-mm-dd;#"
'Delete final blank row otherwise will get ,,,, at bottom of CSV
Sheets(stockTicker).Rows(lastRow + 1 & ":" & Sheets(stockTicker).Rows.Count).Delete
'Remove initial ^ in ticker names from Sheets
If Left(stockTicker, 1) = "^" Then
ActiveSheet.Name = Replace(stockTicker, "^", "")
Else
ActiveSheet.Name = stockTicker
End If
'Remove hyphens in ticker names from Sheet names, otherwise error in collation
If InStr(stockTicker, "-") > 0 Then
ActiveSheet.Name = Replace(stockTicker, "-", "")
End If
NextIteration:
Next ticker
Application.DisplayAlerts = False
If Sheets("Parameters").Shapes("WriteToCSVCheckBox").ControlFormat.Value = xlOn Then
On Error GoTo ErrorHandler:
Call CopyToCSV
End If
If Sheets("Parameters").Shapes("CollateDataCheckBox").ControlFormat.Value = xlOn Then
On Error GoTo ErrorHandler:
Call CollateData
End If
ErrorHandler:
Worksheets("Parameters").Select
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Worksheets("Parameters").Select
For Each C In ThisWorkbook.Connections
C.Delete
Next
End Sub
Sub CollateData()
Dim ws As Worksheet
Dim i As Integer, first As Integer
Dim maxRow As Integer
Dim maxTickerWS As Worksheet
maxRow = 0
For Each ws In Worksheets
If ws.Name <> "Parameters" Then
If ws.UsedRange.Rows.Count > maxRow Then
maxRow = ws.UsedRange.Rows.Count
Set maxTickerWS = ws
End If
End If
Next
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "Open"
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "High"
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "Low"
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "Close"
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "Volume"
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "Adjusted Close"
i = 1
maxTickerWS.Range("A2", "B" & maxRow).Copy Destination:=Sheets("Open").Cells(1, i)
Sheets("Open").Cells(1, i + 1) = maxTickerWS.Name
maxTickerWS.Range("A2", "a" & maxRow).Copy Destination:=Sheets("High").Cells(1, i)
maxTickerWS.Range("c2", "c" & maxRow).Copy Destination:=Sheets("High").Cells(1, i + 1)
Sheets("High").Cells(1, i + 1) = maxTickerWS.Name
maxTickerWS.Range("A2", "a" & maxRow).Copy Destination:=Sheets("Low").Cells(1, i)
maxTickerWS.Range("d2", "d" & maxRow).Copy Destination:=Sheets("Low").Cells(1, i + 1)
Sheets("Low").Cells(1, i + 1) = maxTickerWS.Name
maxTickerWS.Range("A2", "a" & maxRow).Copy Destination:=Sheets("Close").Cells(1, i)
maxTickerWS.Range("e2", "e" & maxRow).Copy Destination:=Sheets("Close").Cells(1, i + 1)
Sheets("Close").Cells(1, i + 1) = maxTickerWS.Name
maxTickerWS.Range("A2", "a" & maxRow).Copy Destination:=Sheets("Volume").Cells(1, i)
maxTickerWS.Range("f2", "f" & maxRow).Copy Destination:=Sheets("Volume").Cells(1, i + 1)
Sheets("Volume").Cells(1, i + 1) = maxTickerWS.Name
maxTickerWS.Range("A2", "a" & maxRow).Copy Destination:=Sheets("Adjusted Close").Cells(1, i)
maxTickerWS.Range("g2", "g" & maxRow).Copy Destination:=Sheets("Adjusted Close").Cells(1, i + 1)
Sheets("Adjusted Close").Cells(1, i + 1) = maxTickerWS.Name
i = i + 2
For Each ws In Worksheets
If ws.Name <> "Parameters" And ws.Name <> "About" And ws.Name <> maxTickerWS.Name And ws.Name <> "Open" And ws.Name <> "High" And ws.Name <> "Low" And ws.Name <> "Close" And ws.Name <> "Volume" And ws.Name <> "Adjusted Close" Then
Sheets("Open").Cells(1, i) = ws.Name
Sheets("Open").Range(Sheets("Open").Cells(2, i), Sheets("Open").Cells(maxRow - 1, i)).Formula = _
"=vlookup(A2," & ws.Name & "!A$2:G$" & maxRow & ",2,0)"
Sheets("High").Cells(1, i) = ws.Name
Sheets("High").Range(Sheets("High").Cells(2, i), Sheets("High").Cells(maxRow - 1, i)).Formula = _
"=vlookup(A2," & ws.Name & "!A$2:G$" & maxRow & ",3,0)"
Sheets("Low").Cells(1, i) = ws.Name
Sheets("Low").Range(Sheets("Low").Cells(2, i), Sheets("Low").Cells(maxRow - 1, i)).Formula = _
"=vlookup(A2," & ws.Name & "!A$2:G$" & maxRow & ",4,0)"
Sheets("Close").Cells(1, i) = ws.Name
Sheets("Close").Range(Sheets("Close").Cells(2, i), Sheets("Close").Cells(maxRow - 1, i)).Formula = _
"=vlookup(A2," & ws.Name & "!A$2:G$" & maxRow & ",5,0)"
Sheets("Volume").Cells(1, i) = ws.Name
Sheets("Volume").Range(Sheets("Volume").Cells(2, i), Sheets("Volume").Cells(maxRow - 1, i)).Formula = _
"=vlookup(A2," & ws.Name & "!A$2:G$" & maxRow & ",6,0)"
Sheets("Adjusted Close").Cells(1, i) = ws.Name
Sheets("Adjusted Close").Range(Sheets("Adjusted Close").Cells(2, i), Sheets("Adjusted Close").Cells(maxRow - 1, i)).Formula = _
"=vlookup(A2," & ws.Name & "!A$2:G$" & maxRow & ",7,0)"
i = i + 1
End If
Next
On Error Resume Next
Sheets("Open").UsedRange.SpecialCells(xlFormulas, xlErrors).Clear
Sheets("Close").UsedRange.SpecialCells(xlFormulas, xlErrors).Clear
Sheets("High").UsedRange.SpecialCells(xlFormulas, xlErrors).Clear
Sheets("Low").UsedRange.SpecialCells(xlFormulas, xlErrors).Clear
Sheets("Volume").UsedRange.SpecialCells(xlFormulas, xlErrors).Clear
Sheets("Adjusted Close").UsedRange.SpecialCells(xlFormulas, xlErrors).Clear
On Error GoTo 0
Sheets("Open").Columns("A:A").EntireColumn.AutoFit
Sheets("High").Columns("A:A").EntireColumn.AutoFit
Sheets("Low").Columns("A:A").EntireColumn.AutoFit
Sheets("Close").Columns("A:A").EntireColumn.AutoFit
Sheets("Volume").Columns("A:A").EntireColumn.AutoFit
Sheets("Adjusted Close").Columns("A:A").EntireColumn.AutoFit
End Sub
Sub SuccessList(ByVal stockTicker As String, ByVal numStockSuccess As Integer)
Sheets("Parameters").Range("L" & 10 + numStockSuccess) = stockTicker
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlDiagonalDown).LineStyle = xlNone
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlDiagonalUp).LineStyle = xlNone
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlEdgeLeft).LineStyle = xlNone
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlEdgeTop).LineStyle = xlNone
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlEdgeBottom).LineStyle = xlNone
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlEdgeRight).LineStyle = xlNone
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlInsideVertical).LineStyle = xlNone
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlInsideHorizontal).LineStyle = xlNone
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlDiagonalDown).LineStyle = xlNone
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlDiagonalUp).LineStyle = xlNone
With Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlInsideVertical).LineStyle = xlNone
Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Borders(xlInsideHorizontal).LineStyle = xlNone
With Sheets("Parameters").Range("L10:L" & 10 + numStockSuccess).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
End Sub
Sub ErrorList(ByVal stockTicker As String, ByVal numStockErrors As Integer)
Sheets("Parameters").Range("J" & 10 + numStockErrors) = stockTicker
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlDiagonalDown).LineStyle = xlNone
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlDiagonalUp).LineStyle = xlNone
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlEdgeLeft).LineStyle = xlNone
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlEdgeTop).LineStyle = xlNone
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlEdgeBottom).LineStyle = xlNone
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlEdgeRight).LineStyle = xlNone
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlInsideVertical).LineStyle = xlNone
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlInsideHorizontal).LineStyle = xlNone
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlDiagonalDown).LineStyle = xlNone
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlDiagonalUp).LineStyle = xlNone
With Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlInsideVertical).LineStyle = xlNone
Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Borders(xlInsideHorizontal).LineStyle = xlNone
With Sheets("Parameters").Range("J10:J" & 10 + numStockErrors).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
End Sub
Sub ClearErrorList(ByVal lastErrorRow As Integer)
If lastErrorRow > 10 Then
Worksheets("Parameters").Range("J11:J" & lastErrorRow).Clear
With Sheets("Parameters").Range("J10").Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("J10").Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("J10").Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("J10").Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
End If
End Sub
Sub ClearSuccessList(ByVal lastSuccessRow As Integer)
If lastSuccessRow > 10 Then
Worksheets("Parameters").Range("L11:L" & lastSuccessRow).Clear
With Sheets("Parameters").Range("L10").Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("L10").Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("L10").Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
With Sheets("Parameters").Range("L10").Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
End If
End Sub
Sub CopyToCSV()
Dim MyPath As String
Dim MyFileName As String
dateFrom = Worksheets("Parameters").Range("$b$5")
dateTo = Worksheets("Parameters").Range("$b$6")
frequency = Worksheets("Parameters").Range("$b$7")
MyPath = Worksheets("Parameters").Range("$b$8")
For Each ws In Worksheets
If ws.Name <> "Parameters" And ws.Name <> "About" Then
ticker = ws.Name
MyFileName = ticker & " " & Format(dateFrom, "dd-mm-yyyy") & " - " & Format(dateTo, "dd-mm-yyyy") & " " & frequency
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets(ticker).Copy
With ActiveWorkbook
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False
.Close False
End With
End If
Next
End Sub
You should set header user-agent to emulate browser
For examble Google Chrome
let
Source = Web.Page(Web.Contents("https://finance.yahoo.com/quote/AAL/history?p=AAL", [Headers=[#"user-agent"="Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"]])),
Data0 = Source{0}[Data]
in
Data0
First time post here, but found the site to be incredibly useful in the past.
I've written a macro to copy data from one worksheet to another, sort A->Z on two columns and then remove duplicate entries, before applying some formatting. It was working a couple of weeks ago, but has stopped working since I decided to replace .Select statements with defined worksheets and ranges (considered good practice from what I've read).
Currently I'm getting a run-time 1004 error (application-defined or object-defined error) on the following line:
desMdWs.Range("A6:D" & (Range("A" & Rows.Count).End(xlUp).Row)).RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
Full sub code below:
Sub UpdateMasterDataList(resWs, mdWs, estWs)
'
' UpdateMasterDataList Macro
' Updates the ATC Master Data tab with any new exceptions found
'
'
' Copy unique values from ATC results list to Remediation Master Data list
'
Dim srcWs As Worksheet
Dim srcRng As Range
Dim desMdWs As Worksheet
Dim desMdRng As Range
Dim desEstWs As Worksheet
Dim desEstRng As Range
Dim LastRow As Long
' Define worksheets to copy from and to
Set srcWs = resWs
Set desMdWs = mdWs
Set desEstWs = estWs
' Define cell ranges to copy from and to
Set srcRng = srcWs.Range("B2:C" & (Range("B" & Rows.Count).End(xlUp).Row))
Set desMdRng = desMdWs.Range("A" & (Range("A6").End(xlDown).Offset(1).Row))
Set desEstRng = desEstWs.Range("A8")
' Perform copy and paste
'Dim srcArray() As Variant
'srcArray = Range("srcRng")
'Dim i As Long
'For i = LBound(srcArray, 1) To UBound(srcArray, 1)
' Debug.Print "srcRng = " & srcArray(i, 1)
'Next
'
'For Each strval In desMdRng
' Debug.Print "desMdRng = " & desMdRng.Value
'Next
srcRng.Copy
desMdRng.PasteSpecial Paste:=xlPasteValues
'
' Sort the list A-Z
'
'desMdWs.Range ("A3:B" & (Range("B" & Rows.Count).End(xlUp).Row)) 'not needed
desMdWs.Sort.SortFields.Clear
desMdWs.Sort.SortFields.Add Key:= _
Range("A6:A" & (Range("A" & Rows.Count).End(xlUp).Row)), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
desMdWs.Sort.SortFields.Add Key:= _
Range("B6:B" & (Range("B" & Rows.Count).End(xlUp).Row)), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With desMdWs.Sort
.SetRange Range("A6:B" & (Range("B" & Rows.Count).End(xlUp).Row))
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'
' Remove duplicates from the list
'
desMdWs.Range("A6:D" & (Range("A" & Rows.Count).End(xlUp).Row)).RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
'
' Autofit the columns
'
desMdWs.Columns("A:A").EntireColumn.AutoFit
desMdWs.Columns("B:B").EntireColumn.AutoFit
'
' Add borders
'
Dim desMdTab As Range
Set desMdTab = desMdWs.Range("A6:D" & (Range("A" & Rows.Count).End(xlUp).Row))
desMdTab.Borders(xlDiagonalDown).LineStyle = xlNone
desMdTab.Borders(xlDiagonalUp).LineStyle = xlNone
With desMdTab.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With desMdTab.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With desMdTab.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With desMdTab.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With desMdTab.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With desMdTab.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
desMdWs.Range("D7").AutoFill Destination:=desMdWs.Range("D" & (Range("D" & Rows.Count).End(xlUp).Offset(1).Row) & ":D" & (Range("A" & Rows.Count).End(xlUp).Row)), Type:=xlFillDefault
End Sub
If anyone can spot where I'm going wrong it would be greatly appreciated.
Cheers,
James
Your Range("A" & Rows.Count).End(xlUp).Row doesn't have its sheet specified, that is why VBA is not finding it.
Try
desMdWs.Range("A" & Rows.Count).End(xlDown).Row
with xlDown instead of up, which will give you the last non empty row. (from what I've gathered, xlDown is the equivalent of ctrl + down)