VBA will not Refresh Queries - excel

Backstory:
I am currently working on a "make-shift" database using excel. I will have one central excel workbook which will house the tables on separate sheets storing data. Other workbooks will interface with this database excel workbook and will input new lines or replace existing lines in the tables by each user interface.
The user-interface workbooks will have query tables pulling from the database workbook tables as needed to provide the users with information.
I am sure there must be a better way of doing this. Any tips tricks or pointers are much appreciated.
Problem:
I have written in my VBA Database Input code to Refresh All queries however it does not update the queries.
I have made a separate sub to update queries but when it is called by the Databse Input code it does not.
Sub Refresh_Queries
Dim ActWB as Object
Set ActWB = ThisWorkbook
ActWB.RefreshAll
End Sub

Are these actual query objects, or something else, perhaps? Make sure you are acting on the correct type of object. Maybe these are workbook connections. Just making a guess here...
Sub Something()
Dim Connection As Variant
For Each Connection In ActiveWorkbook.Connections
Connection.OLEDBConnection.BackgroundQuery = False
Connection.Refresh
Next Connection
End Sub
Or...
Sub Workbook_RefreshAll()
ActiveWorkbook.RefreshAll
End Sub
I hav seen some weird things in the past, like doing a single refresh doesn't work, but doing it a second time works perfectly fine. See the link below for some additional ideas of what you can do to refresh queries, connections, and the like.
https://analysistabs.com/vba-code/workbook/m/refreshall/

Related

Paste/Copy Range of Cells from Excel to a Bookmark in Word using WORD VBA

I am looking at inserting/pasting a range of text data (40 columns) from Excel into bookmarks in Word. Most of the answers are done using Excel VBA, which is so not practical for my use case as I will have the Word document open, add a button that would run this 'import data' macro. I actually already have a button in the doc that inserts images into bookmarks, so that's one more reason I don't want to do it via Excel VBA.
I know this is not great code, but for the lack of definite leads, I'm throwing it here and hope that this gives you an idea of what I'm trying to achieve:
Sub ImportData()
Workbooks.Open ("\Book2.xlsm")
ActiveWindow.WindowState = xlMinimized
ThisWorkbook.Activate
Windows("Book2.xlsm").Activate
Range("A1:AF1").Select
Selection.Copy
Documents("test.docm").Activate
Selection.GoTo What:=wdGoToBookmark, Name:="Overlay_1"
Selection.Paste
End Sub
PS: It would be great if I could sort of 'transpose' the 40 columns into rows as it is pasted in Word.
Here's an update to my code based off #Variatus 's advice:
Sub ImportData()
Dim wb As Workbooks
Dim ws As Worksheets
Dim objSheet As Object
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
wb.Open ("C:\Users\pc\Documents\Book2.xlsm")
Set objSheet = CreateObject("Excel.Application")
ActiveWindow.WindowState = xlMinimized
Set ws = Workbooks("Book2.xlsm").Sheets("Sheet1")
ws.Range("A1").Value.Copy
With objWord.ActiveDocument
.Bookmarks("Bookmark_1").Range.Text = ws.Range("A1").Value
End With
End Sub
I'm getting this error:
Runtime Error '91':
Object variable or With block variable not set.
Notice how I stuck with a single cell reference for now (A1). I'll just update my code as I learn along the way :)
When you click the button in your Word document you want the following sequence to be initiated.
Create an Excel application object. Make sure that a reference to Excel has been set (VBE > Tools > References) so that Excel's VBA objects are available.
Using the Excel application object, open the workbook. Create an object. Place the object in an invisible window.
Definitely forget about activating or selecting anything in either the workbook or your Word document. The latter is active and remains active from beginning to end. The bookmarks are points in your document you can reference and manipulate by name without selecting them. The Excel workbook is invisible. You can access any part of it using the Range object.
The data you want from your workbook are contained in Worksheets. Be sure to create an object for the worksheet you are about to draw data from.
Excel tables don't translate very well into Word tables. If you do want to go that way I suggest that you use VBA to create the table you want in Excel (transpose the data before you import them into Word). However, you may find it easier to first create the tables you want in Word and then just copy values from your Excel source into the word tables. That would involve taking one cell value at a time and placing it into one Word table cell. Transposing would be done by the algorithm you employ.
Close the workbook. Quit the Excel application. Set the Excel application = Nothing. At the end of your macro everything is as it was before except that your document has data in it which it didn't have before.
Each of the above six points will lead you to at least one question which you can ask here after you have googled the subject and written some code. In fact, I strongly urge you to create one Main procedure (the one which responds to your button click) and let that procedure call various subs which carry out the individual tasks and functions to support the subs. The smaller the parts you create the easier it is to write the code, to find questions to ask and get answers to them. If you plan your project well expect to have about 12 procedures in it by the time you are done. Good luck!

Excel Macro, Sending user's data

So I am currently studying SQL Server but right now I am just working a standard office admin job while I'm studying.
I never really made macro's before and little knowledge on VB but decided to design a macro for work to make things a bit easier for my team.
The macro just very simply allows the user to enter data, stats etc and gives the percentage or average statistic resulting in a total letting the user know if the statistics have been hit that day, week, month etc.
It works well but I would like to add a "SUBMIT" button that when a user clicked it would send the data they have entered in specified cells to myself. I am not sure how to go about it, If needed I don't have access to systems like SQL, Visual Studio etc in work as said just basic admin job at the moment.
Would It need to be submitted as a CSV? or could it be submitted from the user's sheet straight onto another macro I have designed giving the results for the whole team? As said I am totally new to this idea.
Cheers Guys.
Awright, according to what you may need in a very simple approach, the first thing you need to do it's to know the cells where they're going to enter info (care with ranges ), let's assume for this example that whe only had one data entered in the first cell of the team worksheet. So, create a button called 'button1' or as you wish and on the click event use this code :
Private Sub button1_click()
Teamsheet.Cells(row,column) = Yoursheet.Cells(destinyrow,destinycolumn)
End Sub
That would copy the value from one sheet to another, now, if you had you sheet locked via password, you must unlock it before doing that,then lock it again so code would be like this :
Private Sub button1_click()
On Error Resume Next
yoursheet.unprotect password:="yourpassword"
Teamsheet.Cells(row,column) = Yoursheet.Cells(destinyrow,destinycolumn)
On Error Resume Next
yoursheet.PROTECT password:="yourpassword"
End Sub
I clarify that this is a very simple approach, so, if you're using specific cells you can copy one by one and this would do (so you can make anny calculation son your admin sheet), but when you're copying ranges should be like this :
Teamsheet.Range("A1:D3").Value = yoursheet.Range("A1:D3").Value
Also, always consider how they enter this data you need.
UPDATE :
Let's say you have a team workbook and yours is admin_workbook, concept it's similar. This code will do what you need but both workbooks should be at the same folder or path :
Private Sub button1_click()
Var_data = Teamsheet.Cells(row,column)
Application.ScreenUpdating = False
Workbooks.Open Filename:=ThisWorkbook.Path & "\admin_workbook.xls"
ThisWorkbook.Activate
Admin_sheet.Cells(destinyrow,destinycolumn) = var_data
Workbooks("admin_workbook.xls").Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub
First you capture data on a var, then you open your admin book, put the data on the cell you want and close that workbook saving changes (you decide if you keep this line or mantain the workbook open and save manually). Also, Application.screenupdating it's a line that helps your screen doesn't flick when changing between workbooks.
Hope it helps friend !

How can I post-process the data from an Excel web query when the query is complete?

As a spreadsheet developer, I am trying to stitch together two sets of rows: one from a web query to a web service I own, and the other a set of manual rows added by the spreadsheet's user (not me).
Excel's built in Web Query / Connections object only provides two modes: I can turn on "Enable background refresh" which makes the web query asynchronous, or uncheck it.
With it unchecked, Excel freezes up while the query executes, which is undesireable. With it checked, there doesn't seem to be any kind of callback or event hook available to be notified, so that I can operate against the refreshed web data.
Is there another way to do this?
An Excel web query utilizes an object called a QueryTable to carry out the business of retrieving and displaying the data.
A QueryTable can be accessed by VBA.
And just like the chart object a querytable object has events that can only be responded to by using the WithEvents keyword from a class module, like so:
Private WithEvents MyQueryTable As QueryTable
Private Sub MyQueryTable_AfterRefresh(ByVal Success As Boolean)
'Do your post processing here...
End Sub
Excel supports the ability to open a URL as another Excel workbook, via the Workbooks.Open method:
From MSDN:
Sub OpenUSDRatesPage()
Dim objBK As Workbook
Dim objRng As Range
'Open the page as a workbook.
Set objBK = Workbooks.Open("http://www.x-rates.com/tables/USD.HTML")
'Find the Canadian Dollar cell.
Set objRng = objBK.Worksheets(1).Cells.Find("Canadian Dollar")
'Retrieve the exchange rate.
MsgBox "The CAD/USD exchange rate is " & objRng.Offset(-6, -1).Value
End Sub
The call is synchronous, so you can operate on the resulting data in the new workbook immediately after the Open call.
While the workbook is loading, Excel will display a progress bar. When you're done, you can call .Close to close the web data workbook. (e.g., for the MSDN example, you'd call objBK.Close when you're done.)
The caveats of using this approach:
You're on the hook to migrate the data from the web workbook to your own (ThisWorkbook) yourself, unlike a refreshable Excel Web Query that has a set destination.
If your web endpoint has a document name that matches the name of a document open in Excel, the user will get a warning that a document with the same name is open.

Excel 2010: How to change pivot table source data without disconnecting slicers?

I have researched like mad about this, and I'm worried there isn't an answer. But maybe the really smart people on this site can help.
I have two workbooks that work together - Charts.xlsm and Data.xlsm. They are always kept together in the same folder. The Charts.xlsm obviously contains all of my charts, but they are all linked to tables in Data.xlsm for their source. I also have lots of slicers in my Charts.xlsm that are connected to the charts, and they share caches when they are connected to charts with the same data source. The two workbooks are always open at the same time so that the data source reference looks like this: 'Data.xlsm'!Table1
This all works great, until I put these workbooks on another computer (which is why I am doing this so I need to find out how to fix this).
Once the workbooks are closed, the source data references change to a specific location on my harddrive: 'C:\Folder\Data.xlsm'!Table1
If I want to manually change this back to a local reference, I have to first go through and disconnect every single slicer, refresh the tables, then reconnect every slicer. Not a viable solution for my clients.
I would use VBA to change the references every time Charts.xlsm is open, but when I tried it one of two things would happen: either the workbook produced errors that would prevent saving, or Excel would crash completely.
This is the code that works perfectly for disconnecting the slicers, but produces the 'save' error:
Sub Disconnect_Slicers()
Dim oSliceCache As SlicerCache
Dim PT As PivotTable
Dim i As Long
For Each oSliceCache In ThisWorkbook.SlicerCaches
With ActiveWorkbook.SlicerCaches(oSliceCache.Name).PivotTables
For i = .Count To 1 Step -1
.RemovePivotTable (.Item(i))
Next i
End With
Next oSliceCache
End Sub
So... I am asking the Excel/VBA geniuses out there if there is any way I can maintain a relative location for my charts when they are looking for Data.xlsm so that no matter what computer I open those workbooks on, they will always be actively linked.
Thank you SO much in advance!
If always both files are in the same folder you could possibly go this way.
A. Switch off auto 'UpdateLinks' of Chart.xlsm file. You could do this once manually or, for safety reason, always when BeforeClose event fires to avoid some possible problems:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.UpdateLinks = xlUpdateLinksNever
End Sub
B. When you open Chart.xlsm change the link to Data.Xlsm using Workbook Open event + additionally refresh links. In this situation we check path to Chart.Xlsm file and search Data.Xlsm in the same folder. I assume that there is only one link to any other file otherwise some changes could be required:
Private Sub Workbook_Open()
'changing first and only one link to new one
Dim a
a = ActiveWorkbook.LinkSources
ThisWorkbook.ChangeLink Name:=a(1), _
NewName:=ThisWorkbook.Path & "\Data.xlsm", Type:=xlExcelLinks
'update the link
ThisWorkbook.UpdateLink Name:=a(1), Type:=xlExcelLinks
End Sub
I admit I do not consider all the risks therefore some test are required.

Get table data in Excel 2007 from query in Access 2007

I have an automated process that is mostly run in Access. But, in the middle, it puts some data in Excel to scrub it into the correct form (it's much faster than doing it in Access), and at the end it opens another Excel file and puts data from some Access queries into the Excel file. For these connections from Excel to Access, I accomplished them all by going into Excel and doing Data --> Get External Data --> From Access, then selecting the Access file and the query I want to get the data from and tell Excel to make it into a Table.
So, I do that one time and then I want to be able to run this automated process that simply refreshes the data. To do this refreshing of the data, I do a line like:
Worksheets("Data").Range("A1").ListObject.QueryTable.Refresh _
BackgroundQuery:=False
The problem is, half the time (and I can't figure out why it does it one time and not another), it says "Do you want to connect to path\filename?" Of course I do, how else would the table refresh? So, this stops the automation. Even if I click Yes, I still can't get it to continue on. If I click Yes, it opens up the Data Link Properties. After I click OK for that, it opens a window titled "Please Enter Microsoft Office Access Database Engine OLE DB Initialization Information". It has info in it, including the path and name of the data source I want to access, but if I click OK, it says, sorry that didn't work, would you like instead to connect to (and then it lists the exact same path and file name it just said didn't work). It repeats the steps I just mentioned, and after that it errors out.
In case it matters, here is the (basic idea) code I use to connect to Excel from Access:
Public Sub ExportToExcel()
Dim ObjXLApp As Object
Dim ObjXLBook As Object
Dim ExcelFilePath As String
ExcelFilePath = CurrentProject.Path & "\"
Set ObjXLApp = CreateObject("Excel.Application")
Set ObjXLBook = ObjXLApp.Workbooks.Open(ExcelFilePath & "filename.xlsm")
ObjXLApp.Visible = True
' Runs the "DataSetUp" macro in the Excel file.
ObjXLApp.Run ("DataSetUp")
' The DataSetUp macro saves the Excel file
' Quit Excel
ObjXLApp.Quit
' Free the memory
Set ObjXLBook = Nothing
Set ObjXLApp = Nothing
End Sub
I have no idea how to fix this! Any help would be much appreciated.
This may be happening because your access database is still open from which the new excel file needs to input data back into. The database cannot be open when this takes place, hense the reason why excel errors and asks for another location to connect to.
So, I would work on generating the needed scrubbing via vba inside access probably.

Resources