I want to create a .VBS file to refresh a table on a spcific worksheet. This table's data comes from an external data source (MS query). Usually, I just right click on the table and go to Refresh. This is what I would like to duplicate in the .VBS file. Is this possible?
I researched this on Stackoverflow (and Google), but I wasn't having luck finding code for the specific worksheet, just for the workbook. I'd like to do this for the specific sheet.
I did research how to access an Excel worksheet through .VBS, and this is what I have so far:
Dim objXLApp, objXLWb, objXLWs
Set objXLApp = CreateObject("Excel.Application")
Set objXLWb = objXLApp.Workbooks.Open("C:\Test\Test.xlsx")
Set objXLWs = objXLWb.Sheets(6)
' This is the code I added to solve my problem
For Each qry In objXLWs.QueryTables
qry.Refresh(false)
Next
objXLWs.Calculate
' End
objXLWb.Save
objXLWb.Close (False)
Set objXLWs = Nothing
Set objXLWb = Nothing
objXLApp.Quit
Set objXLApp = Nothing
MsgBox "Done"
Now, "objXLWs.Refresh" doesn't work. Neither does RefreshAll, RefreshAllData, etc. I get "Object does not support this property or method." I also tried .Calculate, but it doesn't work for this case. I am wondering if there is something that I am missing, or if I have to restructure this code a different way?
Any guidance would be appreciated.
Thanks,
Mark
Try something like
objXLWb.Connections("YourConnectionName").Refresh
Related
I am automating some Excel file creation from Access. I need help with dynamically resetting the pivotcache for all the pivot tables. The first set of code is me testing working code in Excel. Now I want to translate this so that it runs from Access module.
Sub Update_PTSource()
With Sheets("Pivot")
.PivotTables(1).ChangePivotCache ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Sheets("Data").Range("data"))
End With
End Sub
Function pivot_refresh_test()
Dim pt As Variant
Dim wb, ws As Object
Dim strWBName As String
Dim strTabName As String
strWBName = "C:\Users\...\Packaged SKU.xlsb"
strTabName = "Pivot"
Set wb = GetObject(strWBName)
For Each pt In wb.Sheets(strTabName).Pivottables
pt.ChangePivotCache wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=wb.Sheets("Data").Range("data"))
pt.RefreshTable
Next pt
End Function
I'm getting error on pt.ChangePivotCache line with error
invalid procedure call or argument
As far as I can see, you've only made one simple error:
xlDatabase is an Excel enum, and since you're using late bindings, you don't have access to it. You can use it's integer value, 1, instead:
For Each pt In wb.Sheets(strTabName).Pivottables
pt.ChangePivotCache wb.PivotCaches.Create(SourceType:=1, SourceData:=wb.Sheets("Data").Range("data"))
pt.RefreshTable
Next pt
I'm anal about using the least code possible when designing solutions so I found a much easier method to what I wanted to do.
My task was to update and refresh the source data of all my pivot tables. There was one source, multiple pivot tables. I created a dynamic named range for my source for this purpose in my template Excel book that Access was writing into. I never save over the template I just used saveas vba to create the filled copy.
However, since I had created a named range and am modifying always the same template file with Access, I don't need to write a program to change my pivotcache. I can just use 'Change Data Source' in Excel ribbon. The vba code gets much easier. It is just a variation of: ThisWorkbook.RefreshAll. No code loops required!
The whole power of my strategy is the formula that creates my named range. =Data!$A$5:OFFSET(Data!$A$5,COUNTA(Data!$A:$A)-1,52). You just set the first cell of your data, and set how many columns there are for your fields, the rows are automatically adjusted.
I hope this little rant help whoever navigates here. I've been searching a lot for good dynamic pivot table automation but most of the internet has crap info on this.
I am having issues developing this code. I was able to develop the code to copy new data from my workbook to an existing path but am running into issues when trying to retrieve data from the existing path work book.
The concept is that there is a workbook in my system that will be collecting data. The data comes from different users that are working on project information. Once they have completed the project this new information along with existing information gets uploaded back to the workbook collecting that data. The work book collecting the data will always have a defined path. The workbooks that users are working off of will be in multiple places across the system.
The below macro keeps failing on the "Organizer.Sheets("Partnumber_Vendor_Database").Select". I am unsure why.
"Organizer" is the local database the user will use.
"Partnumber_Vendor_File" is the local database the information is stored.
If you can see that this code could be developed better please let me know! :)
Sub Find_Partnumber_Vendor_File()
' This sub is to open the partnumber_Vendor file to update the local database.
On Error Resume Next
Dim Organizer As Workbook
Set Organizer = Application.ActiveWorkbook
Dim Partnumber_Vendor_File As Workbook
Set Partnumber_Vendor_File = Workbooks.Open("S:\Supply Chain\PURCHASING\Forms and Templates\BOM Organizer\Partnumber_Vendor_File.xlsx")
If Err.Number = 1004 Then
MsgBox "Could not open. Check path in VBA"
Exit Sub
End If
If Partnumber_Vendor_File.ReadOnly Then
MsgBox "Sorry, partnumber to vendor database was already in use, try later"
Exit Sub
End If
On Error GoTo 0
Dim Data As Long
Data = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Row
Range("A1:" & "D" & Data).Copy
Organizer.Sheets("Partnumber_Vendor_Database").Select
Range("A1:D1").Select
Selection.Insert Shift:=xlDown
Partnumber_Vendor_File.Close
End Sub
Althoug it is easy to use, avoid ActiveWorkbook, ActiveSheet and Sheets(<Title of the Sheet.).
The problem with the first two is that is hard to tell if the activeworkbook is actually the workbook you are looking for, specially when there are more than 1 workbook open. To workaround this, one solution is the use the Workbooks object to select the correct work book by its NAME (property CodeName). The Same for the Sheets, change the REAL NAMES of the Sheets so you can properlly call them.
The third is basically the same principle. In general, do not use titles of Sheets as references, use the REAL NAME of the object. Use the Property window in the VBA code to change that.
The error may come from 2 situations:
1 - Your selected workbook is not the actual workbook you want to work on.
2 - The Sheet "Partnumber_Vendor_Database" had its title changed or miswritten.
Hope it helps.
Very novice user here, just getting my feet wet. Please excuse this if it's an idiotic question - I'm quite sure what I'm doing yet.
I'm creating a userform with VBA and Excel. I've been successful in learning how to pull information from a pivot table so far, but I've run into a hitch.
When run my userform from another sheet it can't find the pivot table. Here's the code I'm using.
Set PT = ActiveSheet.PivotTables(1)
Works perfectly when I'm one that sheet, but I envision a scenario where I have multiple pivots on different sheets and will want to call info and cross-reference the data.
I thought maybe Set PT = ActiveWorkbook.PivotTables(1) would work, but of course it doesn't. Obviously I don't yet quite understand how to use a pivot table variable.
Does anyone know how I might go about doing this? Thanks so much.
If you open UserForm, workbook with UserForm open will be the active one. If I understand correctly, you want to refer to 1st object of PivotTables collection on a different sheet. To do so, define path of the file with pivot table, example below:
Dim path as string
Dim wbk as workbook
Dim PT As PivotTable
path= "C:\folder1\folder2\yourfile.extension"
set wbk = workbooks.open(path)
Set PT = wbk.worksheets("Sheet1").PivotTables(1)
'do your actions, save the file if you want to keep changes
wbk.close
set wbk = nothing
Alternatively work on all Pivot Tables in your worksheet, instead of:
Set PT = wbk.worksheets("Sheet1").PivotTables(1)
You can use a loop through collection, this example refreshes tables:
For Each PT In wbk.worksheets("Sheet1").PivotTables
PT.RefreshTable
Next PT
I want to export data from a spreadsheet such as name, date of birth, address etc to a letter that I'm writing in word.
I've been following this tutorial:
I've had success in populating the information in word using a command button, but i don't want the ugly grey button in word so i tried making a macro and pasted the same script into a macro vba.
here is the script I'm using when trying to make the macro:
Sub Macro1()
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
Set exWb = objExcel.Workbooks.Open("C:\Users\Admin\Desktop\Case Log.xlsx")
ThisDocument.solicitor.Caption = exWb.Sheets("Sheet1").Cells(4, 3)
exWb.Close
Set exWb = Nothing
End Sub
when i run the macro it highlights the word "solicitor" and displays the message "Compile error: Method or data member not found"
I've checked and rechecked and the label name is correct, it works with the command button, i don't understand why it shouldn't work as a macro.
Any helps would be much appreciated.
I found a native solution for doing this.
Mail Merge!
I set one up and saved it, now everytime I open the document, it loads all the info from the spreadsheet which it is already pointing to.
Thanks for all the suggestions
I've been trying to figure out ways to tell the difference between instances of excel that load the worksheets and ones that don't
Currently I use code to open existing files that looks something like that:
Dim wkbWorkBook as Excel.Workbook
Dim objExcel As Excel.Application
wkbWorkBook = System.Runtime.InteropServices.Marshal.BindToMoniker(filename)
objExcel = wkbWorkBook.Parent
'To make the excel app visible while working with it:
objExcel.Visible = true
What i've noticed while using this code is that If I open a file that exists, but isn't open in excel, when I make the Excel Application visible, the Worksheets aren't visible, but they do exist (I can access worksheets.count and there is an appropriate number of sheets)
I try using Worksheets.Visible but I've noticed it only has an HRESULT error in the place where a "Visible" value would be.
The same error occurs when I try to get the Visible property even when the worksheets are visible (in cases when I BindToMoniker() a file that is currently open in excel.. )
Part of my question is why the BindToMoniker() + Application = workbook.Parent is always giving me an Excel Application without any sheets loaded.. I can't work with it when it's like that..
without gurantees, but I would say worksheets.visible -> won't work, becasue worksheets gives you a list of worksheets.
You cannot apply .visible on that -> you would have to use worksheets(1).visible
Additionally, if there aren't any worksheets, this should fail anyways. you would have to check your count of worksheets first.
Another thing - i don't know if this is possible under vb.net with interop, but maybe you can access specific worksheets through their internal codename - like this:
pobjExcel.table1.visible