I'm trying to import a CSV file into another sheet when I press a button on one sheet.
Here is my code:
Sub historiskAktieData(ticker)
Set ws = ActiveWorkbook.Sheets("HistoriskAktieData")
Dim enddate As Date
Dim StartDate As Date
StartDate = ThisWorkbook.Sheets("Opg. 1").Range("c1").Value
enddate = ThisWorkbook.Sheets("Opg. 1").Range("c2").Value
Symbol = ticker
qurl = "http://ichart.finance.yahoo.com/table.csv?s=" & Symbol & "&a=" & Month(StartDate) - 1 & "&b=" & Day(StartDate) & "&c=" & Year(StartDate) & "&d=" & Month(enddate) - 1 & "&e=" & Day(enddate) & "&f=" & Year(enddate) & "&g=" & "" & "&q=q&y=0&z=" & Symbol & "&x=.csv"
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & qurl _
, Destination:=ws.Range("A1"))
.Name = "table.csv?s=SAP&a=01&b=01&c=14&d=01&e=08&f=16&g=Dateq=q&y=0&z=&x="
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
The problem seems to be this bit:
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & qurl _
, Destination:=ws.Range("A1"))
Hope someone can help. I'm using excel 2010.
From
https://msdn.microsoft.com/en-us/library/office/ff837764.aspx
Destination, Required, Range
The cell in the upper-left corner of the query table destination range
(the range where the resulting query table will be placed). The
destination range must be on the worksheet that contains the
QueryTables object specified by expression.
The QueryTable you are trying to create is in your active sheet (ActiveSheet.QueryTables.Add(...)), yet Destination:=ws.Range("A1") is in general not in the same sheet. Simply write ws.QueryTables.Add(...) instead of ActiveSheet.QueryTables.Add(...).
Related
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.
Sub OPInport(month As Integer, year As Integer)
'
' Macro6 Macro
'F und G
'
Dim selectedRange As Date
Dim WrkBook As Workbook
Dim WrkSheet As Worksheet
Set WrkBook = ActiveWorkbook
Set WrkSheet = ActiveSheet
selectedRange = DateSerial(year, month, 1)
MsgBox selectedRange
WrkBook.Sheets(1).Columns("G:H").NumberFormat = "dd.mm.yyyy"
Range("$A$1").Value = "Change"
Application.CutCopyMode = False
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=OpsApps;UID=Alligatoah;Trusted_Connection=Yes;APP=Microsoft Office 2016;WSID=AT000616;DATABASE=OpsApps" _
, Destination:=Range("$B$1")).QueryTable
.CommandText = Array( _
"SELECT IPM_V_TV_URB.Customer, IPM_V_TV_URB.KNUM, IPM_V_TV_URB.DMRF, IPM_V_TV_URB.HeaderBoM, IPM_V_TV_URB.ProgramReleasedCosts, IPM_V_TV_URB.PlnLaunch, IPM_V_TV_URB.SystemSDate, IPM_V_TV" _
, _
"_URB.ActualCosts" & Chr(13) & "" & Chr(10) & "FROM OpsApps.dbo.IPM_V_TV_URB IPM_V_TV_URB" & Chr(13) & "" & Chr(10) & "WHERE (IPM_V_TV_URB.SystemSDate>={ts selectedRange & 00:00:00'})" _
)
.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_OpsApps"
.Refresh BackgroundQuery:=False
End With
I want to select a specific range of data, but when i try to do that it says "Runtime Error 1004 General ODBC Error" and points out the last line, .Refresh BackgroundQuery:=False. Im quite new to VBA and cant really find a solution to the problem. It only started showing that error message when i changed the date in the where question with selectedDate.
You need to concatenate the selected date into your string - what you are doing currently is using the literal name of the variable as a date.
"_URB.ActualCosts" & Chr(13) & "" & Chr(10) & "FROM OpsApps.dbo.IPM_V_TV_URB IPM_V_TV_URB" & Chr(13) & "" & Chr(10) & "WHERE (IPM_V_TV_URB.SystemSDate>={ts '" & Format(selectedRange, "yyyy-mm-dd") & " 00:00:00'})"
You may need to change the date format used.
Trying to edit some old code left by a previous employee and move to over to an updated system, but by simply copying the code that was wrote originally I get the Runtime Error '1004' - SQL Syntax Error. A copy of the code is below if anyone would like to point me in the right direction??
The part in bold seems to be where it errors...
Sub MIMacro()
'
'
Sheets("MI_Report").Select
Cells.Select
Selection.ClearContents
Dim StartDate As String
Sheets("Date").Select
StartDate = Range("D2").Value & "-" & Range("C2").Value & "-" & Range("B2").Value & " 00:00:00"
Dim EndDate As String
EndDate = Range("D3").Value & "-" & Range("C3").Value & "-" & Range("B3").Value & " 00:00:00"
Sheets("MI_Report").Select
Dim MySql As String
MySql = "SELECT * FROM `W:\MI Reports\Imprint Reports.mdb`.XGSNOR_MI Katie L XGSNOR_MI Katie L WHERE (XGSNOR_MI Katie L.DelDate>={ts '" & StartDate & "'} And XGSNOR_MI Katie L.DelDate<={ts '" & EndDate & "'}) ORDER BY XGSNOR_MI Katie L.JobNo"
With ActiveSheet.QueryTables.Add(Connection:=Array(Array( _
"ODBC;DSN=MS Access Database;DBQ=W:\MI Reports\Imprint Reports.mdb;DefaultDir=W:\MI Reports;DriverId=25;FIL=MS Access;MaxBufferS" _
), Array("ize=2048;PageTimeout=5;")), Destination:=Range("A1"))
.CommandText = Array(MySql)
.Name = "Query from MS Access Database"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = True
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = True
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
**.Refresh BackgroundQuery:=False**
End With
Columns("E:E").Select
Selection.NumberFormat = "General"
Columns("C:C").Select
Selection.NumberFormat = "m/d/yyyy"
Range("A1").Select
Selection.End(xlDown).Select
lr1 = Selection.Row
Range("G1").Select
ActiveCell.FormulaR1C1 = "Cost"
Range("H1").Select
ActiveCell.FormulaR1C1 = "Total Pick Cost"
Range("G2").Select
Dim cost As Double
Dim extra As Double
Dim total As Double
cost = 7#
extra = 0.9
total = 0#
temp = "neworder"
Dim e As Integer
For e = 2 To lr1
If temp = "neworder" Then
temp = Range("A" & e).Value
Range("G" & e).Select
ActiveCell.FormulaR1C1 = cost
total = total + cost
Else
temp = Range("A" & e).Value
Range("G" & e).Select
ActiveCell.FormulaR1C1 = extra
total = total + extra
End If
temp2 = Range("A" & e + 1).Value
If temp <> temp2 Then
temp = "neworder"
Range("H" & e).Select
ActiveCell.FormulaR1C1 = total
total = 0
End If
Next e
Columns("G:H").Select
Selection.NumberFormat = "$#,##0.00"
Range("A1").Select
End Sub
I'm not that familiar with ODBC sequences that are used in that query, so no guarantees this will work:
Replace the MySql = line with
MySql = "SELECT * FROM [XGSNOR_MI Katie L] WHERE ([XGSNOR_MI Katie L].DelDate>={ts '" & StartDate & "'} And [XGSNOR_MI Katie L].DelDate<={ts '" & EndDate & "'}) ORDER BY [XGSNOR_MI Katie L].JobNo"
Also: the following lines should be corrected:
With ActiveSheet.QueryTables.Add(Connection:= _
"ODBC;DSN=MS Access Database;DBQ=W:\MI Reports\Imprint Reports.mdb;DefaultDir=W:\MI Reports;DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;", _
Destination:=Range("A1"))
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") & "'}))"
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 =)