.refresh BackgroundQuery:=False error 1004 - vba

i'm fighting with a problem..
i've got a VBA macro in excel 2013 (made in 2007 and worked fine in 2010)
it's scripted in SQL.
here is a bit of the code where the error is
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DRIVER=SQL Server Native Client 10.0;SERVER=APP14A\ISAHSERVER;UID=reader;PWD=reader;;DATABASE=ProduktieDB;", Destination _
:=Range("$A$7")).QueryTable
.CommandText = Array( _
"SELECT T_DossierMain.OrdNr, T_DossierDetail.DetailCode, T_DossierDetail.Description, T_DossierDetail.PartCode, T_DossierDetail.CalcQty, T_DossierDetail.DiscPerc, T_DossierDetail.CurrPrice" & Chr(13) & "" & Chr(10) & "FROM ProduktieDB.dbo.T_DossierDetail T_DossierDetail, ProduktieDB" _
, _
".dbo.T_DossierMain T_DossierMain" & Chr(13) & "" & Chr(10) & "WHERE T_DossierDetail.DossierCode = T_DossierMain.DossierCode AND ((T_DossierMain.OrdNr= '" & VariableOrderNo & "' ))" _
)
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Hoofdregels_Ophalen"
.Refresh BackgroundQuery:=False
End With
If IsEmpty(Range("A8").Value) Then
MsgBox "De order bestaat niet of heeft geen regels!"
Exit Sub
End If
so the problem is that i'm getting the error on the line ".refresh BackgroundQuery:=False
and if i remove that line, it will keep printing stuff
help?
regards,
michael
EDIT: i've found the problem.. this macro was made in 2007 so the only thing i had to do was changing the ".PreserveFormatting = False > True
thanks anyway =)

Related

Using VBA for Excel: Pulling data from ODBC SQL, how do use a value of "one year before today"?

I recorded a macro that works fine, but I want to use a dynamic date so I don't have to enter it every time. I want to use the WHERE statement to pull records between today and one year prior to today. I had to submit specific date ranges when I recorded the macro, and I want to replace the timestamp with something dynamic, but CURRENT_DATE didn't work (syntax error) and TIMESTAMPADD(SQL_TSI_YEAR, -1, CURRENT_DATE) didn't work (syntax error). The macro recorded as such:
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DRIVER={Centura SQLBase 3.5 32-bit Driver -NT & Win95};UID=ODBC;;DB=CAM32;SRVR=01CAM001A" _
, Destination:=Range("$A$1")).QueryTable
.CommandText = Array( _
"SELECT SALES_LOG_DETAIL.STORE_NUMBER, SALES_LOG_DETAIL.DATE_TIME, SALES_LOG_DETAIL.ITEM_NUMBER, SALES_LOG_DETAIL.QUANTITY, SALES_LOG_DETAIL.PRICE_PAID" & Chr(13) & "" & Chr(10) & "FROM SYSADM.SALES_LOG_DETAIL SALES_LOG_DETAIL" & Chr(13) & "" & Chr(10) & "W" _
, _
"HERE (SALES_LOG_DETAIL.STORE_NUMBER>=2 And SALES_LOG_DETAIL.STORE_NUMBER<=11) AND (SALES_LOG_DETAIL.DATE_TIME>={ts '2017-09-11 00:00:00'} And SALES_LOG_DETAIL.DATE_TIME<={ts '2018-09-11 00:00:00'})" & Chr(13) & "" & Chr(10) & "O" _
, "RDER BY SALES_LOG_DETAIL.STORE_NUMBER, SALES_LOG_DETAIL.ITEM_NUMBER")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Sales_Log_All_Stores"
.Refresh BackgroundQuery:=False
End With
I have no idea why it formats it that way, but when I try to change it I get errors.
How do I change that timestamp code to something that will pull the current date and also look back one year?

Excel VBA query fetches 0 for time values from Access database

My VBA query rightly fetches the data from Access to Excel. However, the values for all the Time related fields are coming as zero. What should I do?
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
"ODBC;DSN=MS Access Database;DBQ=D:\Fair\Macro Workings\Genie Trackers\Ac Genie.accdb;DefaultDir=D:\Fair\Macro Workings\Genie Trackers;DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout" _
), Array("=5;PWD="";UID=admin;")), Destination:=Range("$A$1")).QueryTable
.CommandText = Array( _
"SELECT * FROM `D:\Fair\Macro Workings\Genie Trackers\Ac Genie.accdb`.DailyActivities DailyActivities" & Chr(13) & "" & Chr(10) & "WHERE (DailyActivities.`Accountant`='" & UName & "') AND (DailyActivities.`Due Date`<={ts '" & BDate & "'}) " _
)
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Query_from_MS_Access_Database2"
.Refresh BackgroundQuery:=False
End With
ActiveSheet.ListObjects("Table_Query_from_MS_Access_Database2").Unlist
The dates are coming as numbers but when we format it, that is coming right. However, the time fields are showing zero
Screen shot of the excel result
Screen shot of both database and excel result.
Any help highly appreciated.

Changing SQL Column Data type to date in Excel with VBA

The following is the VBA code I am using to query the database. After querying the data base I would like to be able to perform a separate query on the new table I have created. I would like to do this query using TIMES in date format as the parameter. However, when excel loads the information from the database it loads the TIMES column as a text format instead of a date format. This makes querying by saying
.ComandText = Array("SELECT TIMES FROM [QUERY1 WHERE TIMES BETWEEN '24-JUN-17 05:59:00' and '25-JUN-17 02:00:00' ]
give an error.
I know how to change the column format by opening up the query and manually changing the format I am hoping there is a way to do this in VBA
ActiveWorkbook.Queries.Add Name:="Query1", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Odbc.Query(""dsn=Database"", ""SELECT c.IP_VALUE AS """"PRODUCT"""", c.IP_TIME as CTIMES , s.IP_TIME AS TIMES, s.IP_VALUE AS """"Weight""""#(lf)FROM """"Product"""" AS c , """"Weight"""" as s#(lf)#(lf)WHERE c.IP_TIME between '24-JUN-17 05:59:00' AND '29-JUN-17 06:00:00'"")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
Sheets.Add After:=ActiveSheet
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Query1" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT TIMES FROM [Query1]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Query1"
End With

Excel VBA - I want to insert a date in a 'Get external data' query

I have this Sub with which I receive data from external connection. I already specified a date range :
((infactln.dtransact>{d '2015-09-01'}) AND (infact.dtransact<{d '2015-09-30'}))
I want this sub to give the user the possibility to change this date range without going in "Data - Connections - Properties"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
"ODBC;DSN=Visual FoxPro Tables;UID=;;SourceDB=\\serverName\data.dbc;
SourceType=DBC;Exclusive=No;Background" _
), Array("Fetch=Yes;Collate=Machine;Null=Yes;Deleted=Yes;")),
Destination:= _Range("$A$1")).QueryTable.CommandText = Array(
_"SELECT infact.ctransid, infact.ccode, infactln.dtransact,
infactln.ccode, infactln.cdesc, infactln.bqte, infactln.bmontant,
infactln.bcoutant" & Chr(13) & "" & Chr(10) & "FROM infact infact,
infactln infactln" & Chr(13) & "" & Chr(10) & "WHERE infact.kid =" _
, _" infactln.cparentid AND ((infactln.dtransact>{d '2015-09-01'}) AND
(infact.dtransact<{d '2015-09-30'}))" _)
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = True
.BackgroundQuery = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Query_from_Visual_FoxPro_Tables"
.Refresh BackgroundQuery:=False
End With
You can (and should) use Format function:
https://msdn.microsoft.com/en-us/library/office/gg251755.aspx
Than you just give the user opportunity to specify specific dates in some cells, let's say these are "A1" and "B1". You just substitute the date values in your query with
" infactln.cparentid AND ((infactln.dtransact>{d '" & Format(Cells(1, "A"), "yyyy-MM-dd") & "'}) AND
(infact.dtransact<{d '" & Format(Cells(1, "B"), "yyyy-MM-dd") & "'}))"

Replacing the existing sheet in excel 2007 using VBA

Sub testmac()
'
' testmac Macro
'
'
ActiveWorkbook.Names.Add Name:="items", RefersToR1C1:= _
"=Report!R7C8:R486C11"
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
"ODBC;DSN=Excel Files;DBQ=path
), Array("P;DriverId=1046;MaxBufferSize=2048;PageTimeout=5;")), Destination:= _
Range("$A$1")).QueryTable
.CommandText = Array( _
"TRANSFORM first(`Dimension Value Code`)" & Chr(13) & "" & Chr(10) & "SELECT items.`No#`, items.`Description`" & Chr(13) & "" & Chr(10) & "FROM items" & Chr(13) & "" & Chr(10) & "GROUP BY items.`No#`, items.`Description`" & Chr(13) & "" & Chr(10) & "PIVOT `Dimension Code`" _
)
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Query_from_Excel_FilesXY"
.Refresh BackgroundQuery:=False
End With
End Sub
I am trying to make a pivot table with this code. The first try went well as it had no sheets. When I tried for the second time it gave me an error as the sheet already existed with table in it having the same name as the previous one.
The error is
Run-time error '1004': Application-defined or object defined error
When I delete the worksheet created in the previous step and try running the macro again works properly, but it does not works without deleting it.
you can try this at the top:
on error resume next
ActiveWorkbook.Sheets("your sheet").delete
on error goto 0
if it exists, it will be deleted and your code will make the new one. Does it help?