在VBA中从字符串转换为日期并清除自动程序的旧SQL数据输出

时间:2009-07-09 19:37:52

标签: sql excel vba automation

我正在通过VBA构建一个协调工具,它可以自动从我的oracle数据库和工作表中查询。当我运行查询时,我希望用户输入要查询的ITEM(在这种情况下是管道)(工作表有很多项)和结束/开始日期。我无法搞清楚以下内容:

1)正在查询 - 如果返回的值为NULL,我怎么能告诉它打印出“DATA not AVAILABLE”
2)当我查询管道B时,如何清除管道A的旧sql语句/数据输出? 3)我的日期在Oracle中保存为字符串 - 如何将其转换为日期?
谢谢!

这是我到目前为止所做的:

Option Explicit
Option Base 1

Dim cnnObject As ADODB.Connection
Dim rsObject As ADODB.Recordset
Dim strGPOTSConnectionString As String

Dim Pipeline As String
Dim DateStart As Date
Dim DateEnd As Date
Dim strQuery As String

Sub ClickButton2()

Debug.Print ("Button has been clicked")
Pipeline = InputBox("Enter PipeLine", "My Application", "Default Value")
DateStart = InputBox("Enter Start Date", "My Application", DateTime.Date)
DateEnd = InputBox("Enter End Date", "My Application", DateTime.Date + 1)

Range("B1").Value = Pipeline
Range("B2").Value = DateStart
Range("B3").Value = DateEnd

strQuery = "select pipelineflow.lciid lciid, ldate, volume, capacity, status, " & _
"pipeline, station, stationname, drn, state, county, owneroperator, companycode, " & _
"pointcode, pointtypeind, flowdirection, pointname, facilitytype, pointlocator, " & _
"pidgridcode from pipelineflow, pipelineproperties " & _
"where pipelineflow.lciid = pipelineproperties.lciid " & _
"and pipelineflow.audit_active = 1 " & _
"and pipelineproperties.audit_active =1 " & _
"and pipelineflow.ldate >= '" & Format(DateStart, "dd-MMM-yyyy") & "' and pipelineflow.ldate < '" & Format(DateEnd, "dd-MMM-yyyy") & "' " & _
"and pipelineproperties.pipeline = '" & Pipeline & "' "


    Call PullZaiNetData(strQuery)

    Call TieOut

End Sub

Sub PullZaiNetData2(ByVal strQry As String)

    Set cnnObject = New ADODB.Connection
    Set rsObject = New ADODB.Recordset

    strGPOTSConnectionString = "DRIVER={Microsoft ODBC for Oracle}; SERVER=XYZ; PWD=XYZ; UID=XYZ"


    cnnObject.Open strGPOTSConnectionString

    rsObject.Open strQry, cnnObject, adOpenStatic
    Worksheets("ZaiNet Data").Cells(1, 1).CopyFromRecordset rsObject


    rsObject.Close
    cnnObject.Close

    Set rsObject = Nothing
    Set cnnObject = Nothing

End Sub

Sub TieOut()

End Sub

另外,如果我想改变一下,我怎样才能让用户输入日期和管道进入单元格而不是被提示?我知道我应该做类似设置的事情:

startDate = Worksheets("Instructions").Cells(5, 4).Value

但是这可能吗?

1 个答案:

答案 0 :(得分:1)

  1. 要替换空值,可以使用Oracle的NVL函数。例如“SELECT NVL(pipelineflow.lciid,'DATA NOT AVAILABLE')......”

  2. 要清除旧数据,您可以使用工作表(“ZaiNet数据”).Cells.Clear

  3. 要将日期字符串转换为日期,请使用Oracle的TO_DATE函数,例如“SELECT TO_DATE(ldate,'dd-mon-yyyy')...”,其中dd-mon-yyyy是数据库中日期字符串的日期格式。

  4. 只要单元格中的值可以转换为日期,您从代码中读取日期的代码就可以正常工作。您可能希望使用工作表验证来确保用户只能输入有效日期。