After some updating I have been able to come up with a close to working code. One of the only problems that I am encountering is that the macro is not scraping the data from the last page. For yesterday's data there were 6 pages of data, but the macro is only scraping through page 5. But the weird thing is if i were to scrape data with the same code from 2 days ago, I am able to retrieve the data on all either 7 or 8 pages. I am unsure of why this is happening. Any ideas? Here is the updated code.
'Macro to query Delinquency Status Search for DFB Counties
'Run Monday to pull data from Friday
Sub queryActivityDailyMforFWorking()
Dim nextrow As Integer, i As Long
Dim dates
dates = Date - 1
i = 1
Application.ScreenUpdating = False
Application.DisplayStatusBar = True
Do
'i = i + 1
Application.StatusBar = "Processing Page " & i
nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
'lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlToLeft).Column + 1
'With ActiveSheet.QueryTables.Add(Connection:= _
'"URL;https://www.myfloridalicense.com/delinquency_results.asp?SID=&page=" & i + county + x & "&status=NS&send_date=" & dates & "&search_1.x=1", _
'Destination:=Range("A" & nextrow))
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;https://www.myfloridalicense.com/delinquency_results.asp?SID=&page=" & i & "&county_1=11,%2012,%2013,%2014,%2015,%2016,%2017,%2018,%2019,%2020,%2021,%2022,%2023,%2024,%2025,%2026,%2027,%2028,%2080,%2029,%2030,%2031,%2032,%2033,%2034,%2035,%2036,%2037,%2038,%2039,%2040,%2041,%2042,%2043,%2044,%2045,%2046,%2047,%2048,%2049,%2050,%2051,%2052,%2053,%2054,%2055,%2056,%2057,%2058,%2059,%2079,%2060,%2061,%2062,%2063,%2064,%2067,%2068,%2069,%2065,%2066,%2070,%2071,%2072,%2073,%2078,%2074,%2075,%2076,%2077&status=NS&send_date=" & dates & "&search_1.x=1", _
Destination:=Range("A" & nextrow))
'.Name = _
"2015&search_1.x=40&search_1.y=11&date=on&county_1=AL&lic_num_del=&lic_num_rep=&status=NS&biz_name=&owner_name="
.FieldNames = False
.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 = "10"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
'autofit columns
Columns("A:G").Select
Selection.EntireColumn.AutoFit
'check for filter, if not then turn on filter
ActiveSheet.AutoFilterMode = False
If Not ActiveSheet.AutoFilterMode Then
ActiveSheet.Range("A:G").AutoFilter
End If
i = i + 1
End With
ActiveCell.value = ActiveCell.Value * 2
ActiveCell.Offset(1,0).Select
Loop Until IsEmpty(ActiveCell.Value)
Application.StatusBar = False
'Align text left
Cells.Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
End Sub
My solution (maybe add formatting to bring it back to column A):
Sub QueryDelinquencyTest()
Dim nextrow As Integer, i As Integer
Dim dates
dates = Date - 1
Application.ScreenUpdating = False
Do While i < 25 'this is the page range to be captured.
Application.StatusBar = "Processing Page " & i
nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;https://www.myfloridalicense.com/delinquency_results.asp?SID=&page=" & i & "&county_1=AL&status=NS&send_date=" & dates & "&search_1.x=1", _
Destination:=Range("A" & nextrow))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "10"
.WebPreFormattedTextToColumns = False
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=True
End With
i = i + 1
Loop
Cells.Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
End Sub
This is the code that I have so far when declaring a variable for each county.
'Macro to query Delinquency Status Search for DFB Counties
'Run Monday to pull data from Friday
Sub queryActivityDailyMforF()
Dim nextrow As Integer, i As Long
Dim dates
dates = Date - 1
Dim x, county1, county2, county3, county4, county5, county6, county7, county8, county9, county10, county11, county12
county1 = "county_1=16"
county2 = "county_1=21"
county3 = "county_1=23"
county4 = "county_1=32"
county5 = "county_1=36"
county6 = "county_1=41"
county7 = "county_1=46"
county8 = "county_1=53"
county9 = "county_1=54"
county10 = "county_1=57"
county11 = "county_1=60"
county12 = "county_1=66"
'Dim myString
'myString = "No Activity Information Found"
'Dim lastRow As Long
'Dim county
'Dim site As String
'Dim rng As Range
'Dim firstCell As String
'lastRow = Sheets("sheet1").Range("A" & Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
Application.DisplayStatusBar = True
'If Not rng Is Nothing Then firstCell = rng.Address
'Do Until myString <> lastRow And InStr("&county_1=66", "St. Lucie")
Do
'Do While i < 4
'For i = 1 To lastRow
'Set rng = Sheets("sheet2").Range("A:A").find(What:=Cells(i, 1), LookIn:=xlValues, lookAt:=xlPart, SearchOrder:=xlByRows)
'Do While lastRow <> myString
Application.StatusBar = "Processing Page " & i
nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
'With ActiveSheet.QueryTables.Add(Connection:= _
' "URL;https://www.myfloridalicense.com/delinquency_results.asp?SID=&page=" & i & "&county_1=16&county_1=21&county_1=23&county_1=32&county_1=36&county_1=41&county_1=46&county_1=53&county_1=54&county_1=57&county_1=60&county_1=66&status=NS&send_date=" & dates & "&search_1.x=1", _
' Destination:=Range("A" & nextrow))
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;https://www.myfloridalicense.com/delinquency_results.asp?SID=&page=" & i & county & x & "&status=NS&send_date=" & dates & "&search_1.x=1", _
Destination:=Range("A" & nextrow))
'.Name = _
"2015&search_1.x=40&search_1.y=11&date=on&county_1=AL&lic_num_del=&lic_num_rep=&status=NS&biz_name=&owner_name="
.FieldNames = False
.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 = "10"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
'autofit columns
Columns("A:G").Select
Selection.EntireColumn.AutoFit
'check for filter, if not then turn on filter
ActiveSheet.AutoFilterMode = False
If Not ActiveSheet.AutoFilterMode Then
ActiveSheet.Range("A:G").AutoFilter
End If
'If Not rng Is Nothing Then
' If rng.Address = firstCell Then Exit Do
' End If
'site = "https://www.myfloridalicense.com/delinquency_results.asp?SID=&page=" & i & "&county_1=16&county_1=21&county_1=23&county_1=32&county_1=36&county_1=41&county_1=46&county_1=53&county_1=54&county_1=57&county_1=60&county_1=66&status=NS&send_date=" & dates & "&search_1.x=1"
'county = "&coutny_1=66"
End With
'Next
i = i + 1
Loop Until x = 12
x = x + 1
'Loop Until InStr(site, county) And ActiveCell.Value = myString
'Wend
Application.StatusBar = False
'Align text left
Cells.Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
'Next
'Loop
End Sub
Related
I am creating an Macro for four Pivot Table in the same spreadsheet and I am getting the following error :
"Run-time error '1004': The PivotTable field name is not valid. To create a PivotTable report you must use data that is organized as a list of labeled columns. If you are changing the name of a PivotTable field, you must type a new name for the field. "
Please help me, I have tried so many times...
Sub Macro4()
'
' Macro4 Macro
'
'
Application.CutCopyMode = False
lr = Cells(Rows.Count, 1).End(xlUp).Row
lc = Cells(1, Columns.Count).End(xlToLeft).Column
dataWS = ActiveSheet.Name
dataWS1 = ActiveSheet.Name
Sheets.Add
pivotWS = ActiveSheet.Name
pivotWS1 = ActiveSheet.Name
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"'" & dataWS & "'!A1:AP" & lr, Version:=8).CreatePivotTable TableDestination _
:=pivotWS & "!R3C1", TableName:="PivotTable6", DefaultVersion:=8
Sheets(pivotWS).Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable6")
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 1
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlCompactRow
End With
With ActiveSheet.PivotTables("PivotTable6").PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
ActiveSheet.PivotTables("PivotTable6").RepeatAllLabels xlRepeatLabels
ActiveWorkbook.ShowPivotTableFieldList = True
With ActiveSheet.PivotTables("PivotTable6").PivotFields("FUEL_NAME")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
"PivotTable6").PivotFields("QTY"), "Sum of QTY", xlSum
ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
"PivotTable6").PivotFields("COST_AMT"), "Sum of COST_AMT", xlSum
ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
"PivotTable6").PivotFields("SALES_AMT"), "Sum of SALES_AMT", xlSum
ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
"PivotTable6").PivotFields("MGN "), "Sum of MGN ", xlSum
Range("B4:E6").Select
Selection.Style = "Comma"
Selection.NumberFormat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(#_)"
Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(#_)"
Range("E4").Select
ActiveSheet.PivotTables("PivotTable6").CalculatedFields.Add "Fuel CPU", _
"= ('MGN ' /QTY )*100", True
ActiveSheet.PivotTables("PivotTable6").PivotFields("Fuel CPU").Orientation = _
xlDataField
Range("F4:F6").Select
Selection.Style = "Comma"
Range("F4").Select
ActiveSheet.PivotTables("PivotTable6").CalculatedFields.Add "Fuel CPL", _
"= ('MGN ' /SALES_AMT )", True
ActiveSheet.PivotTables("PivotTable6").PivotFields("Fuel CPL").Orientation = _
xlDataField
Range("G4:G6").Select
Selection.Style = "Comma"
Selection.Style = "Percent"
Selection.NumberFormat = "0.0%"
Selection.NumberFormat = "0.00%"
Range("A3:G6").Select
ActiveSheet.PivotTables("PivotTable6").RowAxisLayout xlTabularRow
Range("A8").Select
Sheets(dataWS).Select
Application.CutCopyMode = False
Application.CutCopyMode = False
ActiveWorkbook.Worksheets(pivotWS).PivotTables("PivotTable6").PivotCache. _
CreatePivotTable TableDestination:=pivotWS & "!R9C1", TableName:="PivotTable7" _
, DefaultVersion:=8
Sheets(pivotWS).Select
Cells(9, 1).Select
With ActiveSheet.PivotTables("PivotTable7")
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 1
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlCompactRow
End With
With ActiveSheet.PivotTables("PivotTable7").PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
ActiveSheet.PivotTables("PivotTable7").RepeatAllLabels xlRepeatLabels
With ActiveSheet.PivotTables("PivotTable7").PivotFields("Sales_Rep")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable7").AddDataField ActiveSheet.PivotTables( _
"PivotTable7").PivotFields("QTY"), "Sum of QTY", xlSum
ActiveSheet.PivotTables("PivotTable7").AddDataField ActiveSheet.PivotTables( _
"PivotTable7").PivotFields("COST_AMT"), "Sum of COST_AMT", xlSum
ActiveSheet.PivotTables("PivotTable7").AddDataField ActiveSheet.PivotTables( _
"PivotTable7").PivotFields("SALES_AMT"), "Sum of SALES_AMT", xlSum
ActiveSheet.PivotTables("PivotTable7").AddDataField ActiveSheet.PivotTables( _
"PivotTable7").PivotFields("MGN "), "Sum of MGN ", xlSum
Range("B10:E16").Select
Selection.Style = "Comma"
Selection.NumberFormat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(#_)"
Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(#_)"
Range("E10").Select
ActiveSheet.PivotTables("PivotTable7").CalculatedFields.Add "Sales Rep CPU", _
"= ('MGN ' /QTY )*100", True
ActiveSheet.PivotTables("PivotTable7").PivotFields("Sales Rep CPU"). _
Orientation = xlDataField
Range("F10:F16").Select
Selection.Style = "Comma"
Range("F10").Select
ActiveSheet.PivotTables("PivotTable7").CalculatedFields.Add "Sales Rep CPL", _
"= ('MGN ' /SALES_AMT )", True
ActiveSheet.PivotTables("PivotTable7").PivotFields("Sales Rep CPL"). _
Orientation = xlDataField
Range("G10:G16").Select
Selection.Style = "Comma"
Selection.Style = "Percent"
Selection.NumberFormat = "0.0%"
Selection.NumberFormat = "0.00%"
Range("A9:G16").Select
ActiveSheet.PivotTables("PivotTable7").RowAxisLayout xlTabularRow
Range("A17").Select
Sheets(dataWS).Select
Application.CutCopyMode = False
Application.CutCopyMode = False
ActiveWorkbook.Worksheets(pivotWS).PivotTables("PivotTable7").PivotCache. _
CreatePivotTable TableDestination:=pivotWS & "!R19C1", TableName:="PivotTable8" _
, DefaultVersion:=8
Sheets(pivotWS).Select
Cells(19, 1).Select
With ActiveSheet.PivotTables("PivotTable8")
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 1
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlCompactRow
End With
With ActiveSheet.PivotTables("PivotTable8").PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
ActiveSheet.PivotTables("PivotTable8").RepeatAllLabels xlRepeatLabels
With ActiveSheet.PivotTables("PivotTable8").PivotFields("VENDOR_ID")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable8").AddDataField ActiveSheet.PivotTables( _
"PivotTable8").PivotFields("QTY"), "Sum of QTY", xlSum
ActiveSheet.PivotTables("PivotTable8").AddDataField ActiveSheet.PivotTables( _
"PivotTable8").PivotFields("COST_AMT"), "Sum of COST_AMT", xlSum
ActiveSheet.PivotTables("PivotTable8").AddDataField ActiveSheet.PivotTables( _
"PivotTable8").PivotFields("SALES_AMT"), "Sum of SALES_AMT", xlSum
ActiveSheet.PivotTables("PivotTable8").AddDataField ActiveSheet.PivotTables( _
"PivotTable8").PivotFields("MGN "), "Sum of MGN ", xlSum
Range("B20:E22").Select
Selection.Style = "Comma"
Selection.NumberFormat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(#_)"
Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(#_)"
Range("E20").Select
ActiveSheet.PivotTables("PivotTable8").CalculatedFields.Add "Vendor CPU", _
"= ('MGN ' /QTY )*100", True
ActiveSheet.PivotTables("PivotTable8").PivotFields("Vendor CPU").Orientation = _
xlDataField
Range("F20:F22").Select
Selection.Style = "Comma"
ActiveSheet.PivotTables("PivotTable8").CalculatedFields.Add "Vendor CPL", _
"= ('MGN ' /SALES_AMT )", True
ActiveSheet.PivotTables("PivotTable8").PivotFields("Vendor CPL").Orientation = _
xlDataField
Range("G20:G22").Select
Selection.Style = "Comma"
Selection.Style = "Percent"
Selection.NumberFormat = "0.0%"
Selection.NumberFormat = "0.00%"
Range("A19:G22").Select
ActiveSheet.PivotTables("PivotTable8").RowAxisLayout xlTabularRow
Range("A26").Select
Sheets(dataWS).Select
Range("F10").Select
Application.CutCopyMode = False
Application.CutCopyMode = False
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sep 2022 MTD!R1C1:R4267C42", Version:=8).CreatePivotTable TableDestination _
:=pivotWS1 & "!R25C1", TableName:="PivotTable9", DefaultVersion:=8
Sheets(pivotWS1).Select
Cells(25, 1).Select
With ActiveSheet.PivotTables("PivotTable9")
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 1
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlCompactRow
End With
With ActiveSheet.PivotTables("PivotTable9").PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
ActiveSheet.PivotTables("PivotTable9").RepeatAllLabels xlRepeatLabels
With ActiveSheet.PivotTables("PivotTable9").PivotFields("FUEL_NAME")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable9").AddDataField ActiveSheet.PivotTables( _
"PivotTable9").PivotFields("QTY"), "Sum of QTY", xlSum
ActiveSheet.PivotTables("PivotTable9").AddDataField ActiveSheet.PivotTables( _
"PivotTable9").PivotFields("COST_AMT"), "Sum of COST_AMT", xlSum
ActiveSheet.PivotTables("PivotTable9").AddDataField ActiveSheet.PivotTables( _
"PivotTable9").PivotFields("SALES_AMT"), "Sum of SALES_AMT", xlSum
ActiveSheet.PivotTables("PivotTable9").AddDataField ActiveSheet.PivotTables( _
"PivotTable9").PivotFields("MGN "), "Sum of MGN ", xlSum
Range("B26:E28").Select
Selection.Style = "Comma"
Selection.NumberFormat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(#_)"
Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(#_)"
Range("E26").Select
ActiveSheet.PivotTables("PivotTable9").CalculatedFields.Add "Fuel CPU1", _
"= ('MGN ' /QTY )*100", True
ActiveSheet.PivotTables("PivotTable9").PivotFields("Fuel CPU1").Orientation = _
xlDataField
Range("F26:F28").Select
Selection.Style = "Comma"
Range("F25").Select
ActiveSheet.PivotTables("PivotTable9").CalculatedFields.Add "Fuel CPL1", _
"= ('MGN ' /SALES_AMT )", True
ActiveSheet.PivotTables("PivotTable9").PivotFields("Fuel CPL1").Orientation = _
xlDataField
Range("G26:G28").Select
Selection.Style = "Comma"
Selection.Style = "Percent"
Selection.NumberFormat = "0.0%"
Selection.NumberFormat = "0.00%"
Range("A25:G28").Select
ActiveSheet.PivotTables("PivotTable9").RowAxisLayout xlTabularRow
Sheets(dataWS1).Select
End Sub
I have a code to create the pivot table I need, but I want to add the coding to search each tab for a key word and if found highlight the tab and create the pivot table. Start Search for KeyWord = "XXXXX" in first tab and if found highlight and create pivot below, then continue to next tab, loop until done. If keyword not found do nothing and continue to next tab.
Sub Create pivot()
ActiveSheet.Select
With ActiveWorkbook.ActiveSheet.Tab
.Color = 65535
.TintAndShade = 0
End With
Dim shtSrc As Worksheet, shtDest As Worksheet
Dim pc As PivotCache
Set shtSrc = ActiveSheet
Set shtDest = shtSrc.Parent.Sheets.Add()
shtDest.Name = shtSrc.Name & "-Pivot"
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=shtSrc.Range("A1").CurrentRegion)
pc.CreatePivotTable TableDestination:=shtDest.Range("A3"), _
TableName:="PivotTable1"
With shtDest.PivotTables("PivotTable1")
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 1
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlCompactRow
End With
With ActiveSheet.PivotTables("PivotTable1").PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
ActiveSheet.PivotTables("PivotTable1").RepeatAllLabels xlRepeatLabels
ActiveWorkbook.ShowPivotTableFieldList = True
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Suspense?")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField
ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("APC LC2 Amount"), "Sum of APC LC2
Amount", xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField
ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Partner LC2 Amount"), "Sum of Partner LC2
Amount", _
xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField
ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("LC2 Amount"), _
"Sum of LC2 amount", xlSum
End Sub
I have tried the below code to import csv file to an excel sheet (Courtesty:http://investexcel.net/download-finviz-data/) and it is working fine. After importing the data, data type was not proper. Please see the screenshot.
The zero prefix was removed 2nd column after importing into excel. Is there any property like '.TextFileColumnDataTypes' for QueryTables.Add(Connection:="URL;"... ?
Sub GetWebCsvData()
Dim str As String
Dim myarray() As Variant
'Delete existing data
Sheets("Data").Activate 'Name of sheet the data will be downloaded into. Change as required.
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
str = "http://somedomain.com/filename.csv"
QueryQuote:
With Sheets("Data").QueryTables.Add(Connection:="URL;" & str, Destination:=Sheets("Data").Range("a1"))
.BackgroundQuery = True
.TablesOnlyFromHTML = false
.Refresh BackgroundQuery:=False
.SaveData = True
End With
Sheets("Data").Range("a1").CurrentRegion.TextToColumns Destination:=Sheets("Data").Range("a1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, other:=True, OtherChar:=",", FieldInfo:=Array(1, 2)
Sheets("Data").Columns("A:B").ColumnWidth = 12
Range("A1").Select
End Sub
This worked quite nicely:
Option Explicit
Sub TestMe()
Dim filePath As String: filePath = "C:\\file.csv"
Cells.Delete
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & filePath, _
Destination:=Range("A1"))
.Name = "test"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 2, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
The correct property is .TextFileColumnDataTypes = Array(1, 2, 1, 1, 1, 1, 1, 1, 1, 1). The 2 in the array stands for Text:
Tribute to these guys.
MSDN - QueryTable.TextFileColumnDataTypes 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
Sub ImportFixed()
'
Sheets("Front-Page").Select
Sheets("SPROC").Visible = True
Sheets("SPROC").Select
ThisWorkbook.RefreshALL
DoEvents
'Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False
Sheets("SPROC").Select
Range("J2").Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Master-Data-Sheet").Select
Range("A1914").Select
ActiveSheet.Paste
Sheets("SPROC").Select
Range("N2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Master-Data-Sheet").Columns("N:N").Range("N1914").Paste
Cells.Select
Application.CutCopyMode = False
With Selection.Font
.Size = 9
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
End With
With Selection.Font
.Name = "Calibri"
.Size = 9
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
Columns("A:H").Select
With Selection
.HorizontalAlignment = xlGeneral
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection
.HorizontalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Columns("M:N").Select
With Selection
.HorizontalAlignment = xlGeneral
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection
.HorizontalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("L16108").Select
Range("J2105").Select
Range(Selection, Selection.End(xlDown)).Select
Range("J2137").Select
Range("N2137").Select
Sheets("SPROC").Select
ActiveWindow.SelectedSheets.Visible = False
ActiveWindow.ScrollWorkbookTabs Sheets:=-2
Sheets("Master-Data-Sheet").Select
End Sub
I have a report that has a sheet named SPROC. This sheet is refreshed each Monday and pulls through data for that day from a SQL query (any other data on that sheet is overwritten) . What I then want to do is select ALL the data (Columns A:N - The number of rows changes each week so the range isn't fixed) and paste it into the first blank cell in column A on a sheet named Master-Data-Sheet. This second sheet contains ALL the data for previous weeks and is used to populate ALL my pivot tables and graphs etc on various other worksheets. At present I have recorded a Macro but instead of finding the last blank row, it is using a specific range which means that when I run the macro, it overwrites data in the Master Data file. Any Suggestions?
I have included a copy of the VBA code (it also does a lot of other functions so apologies if it is a little long). I think it is lines 20 and 359 where the issue is occurring but I have no idea what to do to fix it (I have tried ALL manner of different variations).
Pretty classical matter, must have a lot of similar question and please get rid of scrolls and things like this in record macros...
try this :
Sub Macro2()
'
Dim ShIn As Worksheet
Dim ShOut As Worksheet
Set ShIn = ThisWorkbook.Sheets("SPROC")
Set ShOut = ThisWorkbook.Sheets("Master-Data-Sheet")
'ShIn.Cells(2, 1).End(xlToRight).Column
Dim RgTotalInput As String
Dim RgTotalOutput As String
RgTotalInput = "$A$2:$" & ColLet(ShIn.Cells(1, 1).End(xlToRight).Column) & "$" & ShIn.Cells(Rows.Count, 1).End(xlUp).Row
RgTotalOutput = "$A$" & ShOut.Cells(Rows.Count, 1).End(xlUp).Row + 1
ShIn.Range(RgTotalInput).Copy Destination:=ShOut.Range(RgTotalOutput)
End Sub
Public Function ColLet(ByVal ColNb As Integer) As String
Dim ColLetTemp As String
Select Case ColNb
Case Is < 27
ColLetTemp = Chr(64 + ColNb)
Case Is > 26
If Int(ColNb / 26) <> ColNb / 26 Then
ColLetTemp = Chr(64 + Int(ColNb / 26)) & Chr(64 + ColNb - 26 * Int(ColNb / 26))
Else
ColLetTemp = Chr(64 + Int(ColNb / 26) - 1) & Chr(64 + 26)
End If
Case Else
End Select
ColLet = ColLetTemp
End Function