How to reference and refresh a QueryTable in Excel 2016 in VBA - vba

I'm trying to refresh a query on a cell change, however I can't figure out how to reference the query.
My code: Sheets("Roster Query").QueryTables(0).Refresh
Just errors out with:
Run-time error '1004':
Application-defined or object-defined error
I have a sheet named "Roster Filter" that has query table I want to refresh. How can I get that QueryTable and refresh it?
Edit: Also tried:
For Each qt In Sheets("Roster Query").QueryTables
qt.Refresh
Next
This does not error out, but the query is not refreshed.

Query tables are a relic of older versions of Excel, before tables were a thing. Not sure how to even create one in Excel 2007+.
If you added your QT via the Data/Get External Data Ribbon menu, what you added was actually a ListObject.
I tested this on Sheet1, adding a simple query - Excel created the ListObject for me:
In the immediate pane, I get these results:
?Sheet1.QueryTables.Count
0
?Sheet1.ListObjects.Count
1
And I can reproduce your exact same error:
Sheet1.QueryTables(0).Refresh 'runtime error 1004
The error is simply outrageously misleading, that's all - it should really be an index out of bounds.
The solution is to refresh the ListObject instead:
Sheet1.ListObjects(1).Refresh 'works
You can access the underlying QueryTable object via the ListObject, too:
?Sheet1.ListObjects(1).QueryTable.CommandText 'gives you the query

You're seeing an error because the .Item method is base 1, not base 0
For example, this worked for me in Excel 2016:
Sheets("Roster Query").QueryTables(1).Refresh
So if you only have one QueryTable, it would be .QueryTables(1).

Related

Getting runtime error 1004, not sure what I'm doing wrong

So I'm a bit new to excel VBA, and I'm creating a macro to run on financial worksheets. I want to shift the values in the totals to the right place, as they are a column to the left of the actual data (these weren't created by a formula, they were generated by a different program and are fixed text). The shifting I managed to do just fine. The problem here is finding where the totals column is, as it varies between worksheets.
This is what I have so far.
For totalRow = 7 To 2000
With ws
If ws.Visible = True Then
If InStr(Range(totalRow, "A").Value, "Totals:") > 0 Then
Exit For
End If
End If
End With
Next totalRow
Yet for some reason, it's giving me an error when I try to run it. I know it's probably something simple I'm overlooking, because I cannot for the life of me figure out the problem. I've tried using a Do-Until loop, same issue. Is it a problem with the variables I'm using?
Several suggestions:
This is the basic problem:
Error 1004 "Application-defined or Object-defined error"
Look here for several potential issues/potential fixes:
VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range
Use the VBA debugger and step through your macro a line at a time, until you find the specific object it's barfing on:
https://www.techonthenet.com/excel/macros/vba_debug2013.php
EDIT:
Having said that, I think Tim Williams's suggestion is probably spot-on:
You should always scope your Range/Cells calls with a worksheet
object, otherwise they will reference whatever happens to be the
Activesheet.
But PLEASE:
If at all possible, make the effort to learn troubleshooting tools available to you (like the debugger).
One other "useful tips" link I'd urge you to look at:
http://www.jlathamsite.com/Teach/VBA/WritingBulletProofCode.pdf

Excel VBA Application.Interaction

I have some macro code that runs in my BeforeSave event and before it runs I am using the following line.
Application.Interactive = False
When saving the file normally everything works fine. If I select multiple tabs via ctrl/click and try to save I get an error which reads.
Run-time error '1004':
Method 'Interactive' of object '_Application' failed
It seems to me that the Interactive property is not available to set when you have multiple sheets selected. The reason I want to select several sheets and not the entire document is I am doing a save as and selecting PDF.
Any ideas why this would not work or what could be use in place of Application.Interactive?

Run-Time error '32809': Application-defined or object-defined error

All,
I just upgraded to Excel 2013 and am running into a strange issue. I have a macro-enabled workbook that has worked successfully for quite some time now. I was updating some of the code and came across this error (32809) when trying to write to a specific sheet. In troubleshooting, I tried this.
Sheets("Summary").Range("G8").Value = "Test"
This resulted in the same error. Then I tried this.
Debug.Print ActiveSheet.Name
Same error. So I selected another sheet on the workbook and debug.print on the name. Worked fine.
Then I tried this.
Debug.Print Sheets(2).Name (This is the sheet number of the problemic sheet)
Same error. It seems to me that there is some form of corruption with this sheet but I am reticent about deleting and recreating. Any suggestions?
Thanks!
While it wasn't a perfect solution, here is how I finally resolved it. I had a user that was still on Excel 2010 make a copy the corrupt sheet within the same workbook, delete the corrupt sheet, then rename the new sheet to the original name. I was then able to use the workbook in Excel 2013 without issue.
I have a Workbook Open Macro which counts the number of rows in a table on opening so that I can summarize how many records were added or deleted during the data entry session:
Private Sub Workbook_Open()
Dim TotalRows As Integer
TotalRows = Worksheets("Data").ListObjects(1).ListRows.Count
If Range("LastRecordOnStart") <> TotalRows Then Range("LastRecordOnStart") = TotalRows
' Stop
End Sub
I started getting the run-time error '32809' with the following line in the code above highlighted in the debugger every time I opened the workbook...
TotalRows = Worksheets("Data").ListObjects(1).ListRows.Count
Rebooting or opening the workbook on another PC still would not fix it. Even opening a previously saved working copy would give the same error - strange. Note:
While coding, I will periodically save the workbook and use windows explorer to copy a snapshot of the workbook where it creates myworkbook copy(1).xlsm, copy(2).xlsm, etc and if I get a corrupted workbook, I rename it myworkbook.bad.xlsm and rename the latest saved working version (e.g myworkbook copy(6).xlsm to MyWorkbook.xlsm with minimal loss.
When this run-time error occurs though, I've had to rebuild the book several times. It only appears to happen when the workbook crashes after a long session of debugging new code with the Userform open and I have to close excel from the Task Manager.
I read the posts here today and was convinced that it was page related when I could list the listrows count on another sheet and if I converted the Listobject on the "Data" worksheet back to a range and recreated the table, I'd still get the run-time error. To cut a long story short, I tried the following:
Open the workbook
When the error popped up, clicked debug
Right clicked on the "End Sub" line of the WorkBook_Open sub and clicked "Set Next statement"
Pressed F5 to allow the code to finish executing
Saved the workbook and it all works now!
I had another crash with the subsequent run-time error and repeated the steps above and it worked a charm again.

Run-time error '1004' on closing Excel vba 2013

I'm having a run-time error 1004 on closing the excel sheet. Through my research, most of error 1004 happen when the users are trying to copy the sheet by macro or closing the sheet by macro.
In my case, the error appears even when I close the developer tab and create a new excel file. Some resources I found online include the You may receive a "Run-time error 1004" error message when you programmatically set a large array string to a range in Excel 2003 and some other forum posts. However none of them is applicable in my case since I'm trying to close the file by the 'x' button. Please let me know if should describe the question more accurately. Thanks.

VBA Error 457 when using Collection to create a unique list

BACKGROUND:
I am trying to identify how many unique time periods I have from a list of dates that have. Elsewhere, I have seen a method which utilizes collections and error trapping (right term? I mean "On Error Resume Next" in any case) to build the collection with unique values. I have even used this structure successfully in other code that I have written, but in my current circumstance, I am getting an "Error 457: This key is already associated with an element of this collection." Thinking I was using the collection incorrectly, I opened up some older code I wrote 6 months ago (on a different computer for a different company) which uses the same structure and was known to WORK. This older code broke on the same identical error, which it previously did not do. Here is the sample of my work-in-progress code:
Dim rng as range
Dim TimePeriod as Collection
Set TimePeriod = New Collection
For Each rng In Range("I2:I6")
On Error Resume Next
TimePeriod.Add rng.Value, CStr(rng.Value) 'This is where the code breaks
On Error GoTo 0
Next rng
QUESTION:
I'm wondering if there is a setting or a reference library that I am somehow missing that is causing both pieces of code to break, or how to determine that, since both codes are functionally identical, and the previously tested satisfactory code breaks like my work-in-progress. I expected the "On Error Resume Next" to force the loop to pass over the error. Any suggestions?
--Update--
Sample data in range("I2:I6") as follows:
1/21/15
1/21/15
1/21/15
1/23/15
1/27/15
Your code works properly on my Excel 2007, although I would rewrite it to enclose the entire loop within the on error resume next for efficiency.
I suspect you are seeing the errors now because of a mis-set macro option error break.
Check Tools/Options that you have not selected to Break on All Errors
Try getting rid of the On Error Goto 0 line. Take a look at this:
Difference between 'on error goto 0' and 'on error goto -1' -- VBA
It comes from Visual Basic 6, but works pretty much the same in VBA, it appears. Should work if you keep the On Error Resume Next line but eliminate the On Error Goto 0 line.