使用VBA

时间:2017-07-06 11:18:17

标签: excel vba excel-vba odbc

以下是我用来查询数据库的VBA代码。在查询数据库之后,我希望能够对我创建的新表执行单独的查询。我想使用日期格式的TIMES作为参数进行此查询。但是,当excel从数据库加载信息时,它会将TIMES列作为文本格式而不是日期格式加载。这可以通过说

进行查询
 .ComandText = Array("SELECT TIMES FROM [QUERY1 WHERE TIMES BETWEEN '24-JUN-17 05:59:00' and '25-JUN-17 02:00:00' ]  

给出错误。

我知道如何通过打开查询并手动更改格式来更改列格式我希望有一种方法可以在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

0 个答案:

没有答案