Excel ADODB批处理问题

时间:2016-09-06 19:11:15

标签: excel vba adodb

我在excel中编写了以下VBA / ADODB代码,直接运行时工作正常,但是当通过批处理VBS脚本运行时,SQL语句不会被执行。任何想法是什么原因? (Windows 7 / Excel 2012)

如果您对该代码有任何其他意见,请告诉我。 感谢。

Sub RunSQL()

Dim conn As Object, rst As Object, rst2 As Object
Dim strConnection As String, strSQL As String, strSQL2 As String
Dim i As Integer

'start error handler
On Error GoTo ErrorHandler:

Set conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")

'connection string EXTERNAL source
strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _
& "DBQ=C:\Users\Mike\Documents\SourceBook1.xlsx;"

'SQL statement
strSQL = "SELECT col2 FROM [Sheet1$];"

'open connection
conn.Open strConnection

'run SQL
rst.Open strSQL, conn

'write column headings
For i = 1 To rst.Fields.Count
    Worksheets("Sheet1").Cells(1, i) = rst.Fields(i - 1).Name
Next i

'write data rows
Worksheets("Sheet1").Range("A2").CopyFromRecordset rst

'close workbook and save
ActiveWorkbook.Close True

'clean up
rst.Close: conn.Close
Set rst = Nothing: Set conn = Nothing

Exit Sub

ErrorHandler:
ErrorStr = "Error: " & Str(Err.Number) & ", Source: " & Err.Source & ", Description: " & Err.Description

'continue if error in clean up
On Error Resume Next

'clean up
rst.Close: conn.Close
Set rst = Nothing: Set conn = Nothing

'handle error
MsgBox (ErrorStr)

End Sub

这是批量工作......

Option Explicit

On Error Resume Next
ExcelMacroExample

Sub ExcelMacroExample() 
Dim xlApp 
Dim xlBook 

Set xlApp = CreateObject("Excel.Application") 
Set xlBook = xlApp.Workbooks.Open ("C:\Users\Mike\Documents\TargetBook1.xlsm", 0, True) 

xlApp.Run "RunSQL"
xlApp.ActiveWorkbook.Close
xlApp.Quit 

Set xlBook = Nothing 
Set xlApp = Nothing 
End Sub 

0 个答案:

没有答案