将VBA转换为VBScript - 不工作但没有错误

时间:2016-09-01 17:56:39

标签: vba tsql vbscript adodb

我一直关注有关将VBA转换为VBScript的文章和问题,但我现在卡住了。以下代码仍然适用于VBA(如果我删除Sub例程调用)但它不会作为脚本运行。

代码打开与SQL Server的连接以检查表以查看该进程是否已在今天运行并将结果加载到Recordset中。如果该字段设置为No,则会打开Excel工作簿并运行宏。它适用于VBA,但是当我运行与脚本相同的代码时,没有任何事情发生(也没有错误)。

你能看出问题所在吗?非常感谢。

NB。 cmd.CommandText有两行。注释掉的行旨在始终返回No仅用于测试目的。

' Author Steve Wolstencroft
' Inititates the Automated Excel Refresh Procedure
Option Explicit

Pivot_Refresh

Public Function ConnectToSQLDwarfP()
    On Error Resume Next
    ConnectToSQLDwarfP = "Driver={SQL Server Native Client 10.0};Server=DwarfP;Database=DwarfPortable;Trusted_Connection=yes;"
End Function

Public Sub Pivot_Refresh()
    On Error Resume Next

    Dim cnx
    Dim Rst

    Set cnx = New ADODB.Connection
        cnx.ConnectionString = ConnectToSQLDwarfP
        cnx.Open

    Dim cmd

    Set cmd = New ADODB.Command
        cmd.ActiveConnection = cnx
        cmd.CommandType = adCmdText
        cmd.CommandText = "Select Case When max(DwarfPortable.dbo.fn_GetJustDate(pl.StartDateTime)) = DwarfPortable.dbo.fn_GetJustDate(getDate()) Then 'Y'  Else 'N' End as RunToday From ProcessControl.dbo.ProcessLog pl Where pl.ProcessName = 'Excel_Auto_Refresh'"
        'cmd.CommandText = "Select Case When max(pl.StartDateTime) = DwarfPortable.dbo.fn_GetJustDate(getDate()) Then 'Y' Else 'N' End as RunToday From ProcessControl.dbo.ProcessLog pl Where pl.ProcessName = 'Excel_Auto_Refresh'"

    Set Rst = cmd.Execute

    Dim objXL, objBook
    Set objXL = CreateObject("Excel.Application")

    If Rst.Fields("RunToday") = "N" Then
        Set objBook = objXL.Workbooks.Open("\\nch\dfs\SharedArea\HI\Clinical-Informatics\InfoRequestOutputs\Regular-Jobs\Pivot-Refresh\Pivot-Refresh-Control.xls", 0, True)
        objXL.Application.Visible = True

        objXL.Application.Run "'Pivot-Refresh-Control.xls'!Auto_Refresh"

        objXL.ActiveWindow.Close
        objXL.Quit

        Set objBook = Nothing
        Set objXL = Nothing
    End If

End Sub

1 个答案:

答案 0 :(得分:5)

您无法在VBScript中实例化外部对象,例如New ADODB.Connection因为没有对外部库的引用。

adCmdText也喜欢On Error Resume Next。它们将被视为未定义的空变量。

您没有收到任何错误,因为您使用CreateObject关闭了它们。删除它,你会得到你的错误。

确保所有外部对象实例化都使用min-height完成,就像使用Excel一样,并用文字值替换所有外部常量。