Code for pivot table in VBA only works one time - vba

I have a sheet with 1532 rows and 7 columns called "Delayed Students". I want to make a pivot table in the sheet but every time I use my code, I get a
run-time error'438 "Object doesn't support this property or method"
And this area is yellow (.Position =1):
With .PivotFields("FACULTY_ID")
.Orientation = xlDataField
.Postion = 1
But it creates the pivot table anyways. The problem is when i delete the table and try to use the code again it doesn't create the pivot table again. So something must be wrong with my code:
Sub Pivot1()
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Dim PvtTblName As String
Dim pivotTableWs As Worksheet
PvtTblName = "pivotTableName"
Set pivotTableWs = Sheets("Delayed Students")
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Delayed Students!R1C1:R1532C7")
Set PvtTbl = pivotTableWs.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=pivotTableWs.Range("J1"), TableName:=PvtTblName)
With PvtTbl
.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
With .PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
.RepeatAllLabels xlRepeatLabels
With .PivotFields("STUDYBOARD_ID")
.Orientation = xlRowField
.Position = 1
End With
With .PivotFields("FACULTY_ID")
.Orientation = xlDataField
.Postion = 1
End With
End With
End Sub
Hope someone can help me with what i am doing wrong :)

Related

Pivot Table from VBA macro displaying incorrect data

Somehow my Pivot Table created from my VBA script displays different data than when i create the pivot table manually.
My macro does the following:
Database is in sheet 2. Pivot is in sheet 1.
Macro deletes all rows in sheet 2 and adds new data.
M deletes rows containing the current pivot.
M deletes the data-connection for the pivot.
M creates new data-connection for the new data in sheet 2 and creates a new
pivot in sheet 1.
Everything works without errors, but somehow the data is not the same as to when i create the pivot manually.
My guess is that it uses some old data-connection, but im not sure how or how to fix this.
VBA - Code for pivot table creation:
'Delete old pivot
Sheets("Sheet1").Select
Range("A1:C5").Select
Selection.ClearContents
'Create new Connection
ActiveWorkbook.Connections("PivotConnection").Delete
Workbooks("File.xlsm").Connections.Add2 _
"PivotConnection", "", _
"WORKSHEET;*ABSOLUTE PATH*[File.xlsm]Sheet2" _
, "Sheet2!$A:$Q", 7, True, False
'Create new pivot
ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:= _
ActiveWorkbook.Connections("PivotConnection"), Version:=6).CreatePivotTable _
TableDestination:=Worksheets("Sheet1").Cells(1, 1), TableName:="PivotTable3", DefaultVersion:=6
With ActiveSheet.PivotTables("PivotTable3")
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = True
.CompactRowIndent = 1
.VisualTotals = False
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = True
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.DisplayEmptyRow = False
.DisplayEmptyColumn = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.DisplayImmediateItems = True
.ViewCalculatedMembers = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = True
.RowAxisLayout xlCompactRow
End With
ActiveSheet.PivotTables("PivotTable3").PivotCache.RefreshOnFileOpen = False
ActiveSheet.PivotTables("PivotTable3").RepeatAllLabels xlRepeatLabels
Thanks in advance
EDIT:
Just to clarify how the data is incorrect:
The distinct count of a row gives me e.g. 1000
I run the macro and new pivot with modified data is created
Distinct count still shows 1000
Manually created pivot shows e.g. 980 for distinct count

Intermittent VBA macro error

I have written the below code to cycle through my worksheets as a kind of slideshow to use in a sales department. The code works perfectly when I step through in debug mode, however when I run the macro it only works intermittently, occasionally getting to the selecting of the worksheets without having reactivated the screen updating application function.
Here is the code I have created so far:
Sub Runshow()
Dim ws As Worksheet
On Error GoTo exit_
Application.EnableCancelKey = xlErrorHandler
For Each ws In ThisWorkbook.Worksheets
ws.Protect
Next
Application.DisplayFullScreen = True
Application.DisplayFormulaBar = False
ActiveWindow.DisplayWorkbookTabs = False
ActiveWindow.DisplayHeadings = False
ActiveWindow.DisplayGridlines = False
ActiveWindow.DisplayHorizontalScrollBar = False
ActiveWindow.DisplayVerticalScrollBar = False
Application.Calculation = xlManual
Let y = 0
Do Until y = 80
Application.ScreenUpdating = False
Workbooks.Open("c:\users\admin\downloads\crm.xlsx").Activate
Application.Calculate
ActiveWorkbook.Close savechanges = False
Application.ScreenUpdating = True
ThisWorkbook.Activate
Let x = 0
Do Until x = 23
For Each ws In ActiveWorkbook.Worksheets
ws.Select
Application.Wait (Now + TimeValue("00:00:10"))
x = x + 1
Next
Loop
y = y + 1
Loop
exit_:
For Each ws In ThisWorkbook.Worksheets
ws.Unprotect
Next
Application.DisplayFullScreen = False
Application.DisplayFormulaBar = True
ActiveWindow.DisplayWorkbookTabs = True
ActiveWindow.DisplayGridlines = True
ActiveWindow.DisplayHorizontalScrollBar = True
ActiveWindow.DisplayVerticalScrollBar = True
Application.Calculation = xlAutomatic
End Sub
I put together some simple code that does something similar, and works well. You can build out from here - ask any questions if there's anything you don't understand.
Sub Slideshow()
Dim ws As Worksheet
PrepareView True
For Each ws In ThisWorkbook.Worksheets
ws.Activate
Application.Wait (Now + TimeValue("00:00:10"))
Next ws
PrepareView False
End Sub
Function PrepareView(status As Boolean)
If status = True Then
ActiveWindow.DisplayWorkbookTabs = False
ActiveWindow.DisplayHeadings = False
ActiveWindow.DisplayGridlines = False
ActiveWindow.DisplayHorizontalScrollBar = False
ActiveWindow.DisplayVerticalScrollBar = False
ElseIf status = False Then
Application.DisplayFullScreen = False
Application.DisplayFormulaBar = True
ActiveWindow.DisplayWorkbookTabs = True
ActiveWindow.DisplayGridlines = True
ActiveWindow.DisplayHorizontalScrollBar = True
ActiveWindow.DisplayVerticalScrollBar = True
End If
End Function

Data from website passing variable name to URL but not going to the correct website

This code is basically working correctly but for some reason the data it pulls is not changing. As I step through the Name_of_Person variable is changing as I move through the X's and the URL created and used changes every time but it keeps inserting the data from the first query. Any thoughts as to why?
Sub Search_People()
Dim Name_Of_Person As String
Dim URL As String
Dim Dashboard_Sheet As Worksheet
Set Dashboard_Sheet = ThisWorkbook.Sheets("Dashboard")
Dim Data_Sheet As Worksheet
Set Data_Sheet = ThisWorkbook.Sheets("Data")
Dim Data_Dump As Worksheet
Set Data_Dump = ThisWorkbook.Sheets("DataDump")
Dim X As Integer
Dim Y As Integer
Dim Last_Row As Long
Dim Email_Output As Range
Set Email_Output = Data_Dump.Range("A:A")
Dim Cell As Range
Last_Row = Data_Sheet.Cells(Data_Sheet.Rows.Count, 8).End(xlUp).Row
For X = 1 To Last_Row + 1
Name_Of_Person = Data_Sheet.Cells(2 + X, 8)
URL = "URL;" & "https://hn.com/people/"
URL = URL & Name_Of_Person & "%40.com"
With Data_Dump.QueryTables.Add(Connection:= _
URL, _
Destination:=Data_Dump.Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
Set Cell = Email_Output.Find("Email")
Worksheets("Data").Cells(2 + X, 9).Value = Cell
End With
Data_Dump.Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Next X
End Sub
Sub Search_People()
Dim Name_Of_Person As String
Dim URL As String
Dim Dashboard_Sheet As Worksheet
Set Dashboard_Sheet = ThisWorkbook.Sheets("Dashboard")
Dim Data_Sheet As Worksheet
Set Data_Sheet = ThisWorkbook.Sheets("Data")
Dim Data_Dump As Worksheet
Set Data_Dump = ThisWorkbook.Sheets("DataDump")
Dim X As Integer
Dim Y As Integer
Dim Last_Row As Long
Dim Email_Output As Range
Set Email_Output = Data_Dump.Range("A:XFD")
Dim Cell As Range
Application.EnableCancelKey = xlDisabled
Last_Row = Data_Sheet.Cells(Data_Sheet.Rows.Count, 8).End(xlUp).Row
For X = 1 To Last_Row
On Error Resume Next
Name_Of_Person = Data_Sheet.Cells(2 + X, 8)
Application.StatusBar = " Pulling Data for... " & Name_Of_Person
URL = "URL;" & "https://site/"
URL = URL & Name_Of_Person & "site.com"
With Data_Dump.QueryTables.Add(Connection:= _
URL, _
Destination:=Data_Dump.Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
Set Cell = Email_Output.Find("Email")
Worksheets("Data").Cells(2 + X, 9).Value = Cell
Data_Dump.Range("A:A").EntireColumn.Delete
Next X
Application.StatusBar = False
End Sub
This code solved all of the above issues.

Extract match data from this web "http://bet.hkjc.com/football/index.aspx?lang=en"

I want to extract match data from this web site "http://bet.hkjc.com/football/index.aspx?lang=en" using the following code :
Sub Macro4()
' Macro4 Macro
' steve lau 在 28/04/2016 錄製的巨集
baseURL = "http://www.hkjc.com/chinese/news/redirect_odds_ch_football.asp"
baseName = "summary"
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;" & baseURL _
, Destination:=Range("A1"))
End With
With ActiveSheet.QueryTables.Add(Destination:=Range("A1"))
.Name = baseName
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=True
End With
End Sub
But nothing was returned. I think it may due to different frames in the web page. Could anyone can help to figure out how to extract the match details ?
Many thanks.
You can use the following script where I grab the table using a
.document.getElementById("footballmaincontent").getElementsByTagName("table")(2)
and then loop the rows and columns (cells within row) within the table.
Sample results on page on 14/06/2018
Matches output from script:
Code:
Option Explicit
Public Sub GetInfo()
Dim IE As New InternetExplorer, a As HTMLTable
Const URL = "http://bet.hkjc.com/football/index.aspx?lang=en"
Application.ScreenUpdating = True
With IE
.Visible = False
.navigate URL
While .Busy Or .readyState < 4: DoEvents: Wend
Set a = .document.getElementById("footballmaincontent").getElementsByTagName("table")(2)
Dim r As Long, c As Long, iRow As HTMLTableRow, iCell As HTMLTableCell
With ActiveSheet
For Each iRow In a.getElementsByTagName("tr")
For Each iCell In iRow.getElementsByTagName("td")
Select Case iCell.innerText
Case "Home", "Draw", "Away"
Case Else
c = c + 1: .Cells(r + 1, c) = iCell.innerText
End Select
Next iCell
c = 0: r = r + 1
Next iRow
End With
.Quit
End With
Application.ScreenUpdating = True
End Sub
References required (VBE > Tools > References)
HTML Object Library
Microsoft Internet Controls

Looped macro to create a new sheet, rename it, add data from the web, then loop back through until complete

Trying to create a macro to take a spreadsheet with two columns (one with names, the other with a URL to a sheet I need data from), create a new sheet for each row, rename that sheet according to the name in column A, then create a web query in the new sheet according to the URL in column B.
Here's the macro I tried compiling, but it's not working.
Sub CreateSheetsFromAList()
Dim wb As Workbook
Dim src As Worksheet
Dim tgt As Worksheet
Dim MyCell As Range, MyRange As Range, URLCell As Range
Set wb = ThisWorkbook
Set src = wb.Sheets("AllPlayers")
Set MyRange = Sheets("AllPlayers").Range("A1")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
Set URLCell = Sheets("AllPlayers").Range("B1")
Set URLCell = Range(URLCell, URLCell.End(xlDown))
For Each MyCell In MyRange
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = MyCell.Value
With ActiveSheet.QueryTables.Add(Connection:=URLCell, Destination:=Range("$A$2"))
.Name = "2015"
.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 = """pgl_basic"""
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
Next MyCell
End Sub
Made some syntax tweaks that should help as well as error handling if the sheet name already exists. Didn't make any changes to the QueryTable.Add method though.
Sub CreateSheetsFromAList()
Dim wb As Workbook
Dim src As Worksheet
Dim tgt As Worksheet
Dim ActSht As Worksheet
Dim MyCell As Range, MyRange As Range, URLValue As Variant
Set wb = ThisWorkbook
Set src = wb.Sheets("AllPlayers")
Set MyRange = src.Range("A1:A" & src.Range("A" & src.Rows.Count).End(xlUp).Row)
For Each MyCell In MyRange
On Error Resume Next
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = MyCell.Value
If Err.Number > 0 Then
Err.Clear
MsgBox MyCell.Value & " sheet name already exists"
Exit Sub
End If
On Error Goto 0
URLValue = MyCell.Offset(0, 1).Value
Set ActSht = Sheets(Chr(34) & MyCell.Value & Chr(34))
With ActSht.QueryTables.Add(Connection:= "URL;" & URLValue, Destination:=ActSht.Range("A2"))
.Name = "2015"
.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 = """pgl_basic"""
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
Next MyCell
End Sub