|
本帖最后由 betar 于 2016-10-21 10:11 编辑
如题,如何使用Excel VBA SQL 连接带有密码的Excel表格?假设路径指向的工作表带有密码,为123如附件所示。如何用SQL进行连接?求大神指导。
- cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;extended properties=Excel 12.0;Data Source=" & Path
- SQL = "select [Loan Acccout No#] from [Sheet1$A1:DH1048576] "
复制代码
test.zip
(8.15 KB, 下载次数: 41)
感谢大神回复,现在确定的是无法直接用SQL对带有密码的工作簿进行连接。但是还有一种思路是先用workbooks.open把目标工作簿打开,再对已经打开的工作簿进行连接。可惜个人水平有限,代码会报错,还请各路大神不吝赐教。
- Sub test()
- Dim File As Workbook
- Dim Index As Worksheet
- Dim cnn
- Dim rst
- Dim SQL$
- Dim Path, Text1, SheetName As String
-
- Path = ThisWorkbook.Path & ""
- Text1 = "test.xlsx"
- SheetName = "Sheet1"
-
- Set ExcelApp = CreateObject("Excel.Application")
- Set File = ExcelApp.Workbooks.Open(Filename:=Path & Text1, Password:="123")
- Set Index = File.Worksheets(SheetName)
-
- Sheets("Sheet1").Range("a2:e65536").ClearContents
- Sheets("Sheet1").Select
-
- Set cnn = CreateObject("adodb.connection") 'Create DB Connection
- Set rst = CreateObject("adodb.recordset")
- cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;extended properties=Excel 12.0;Data Source=" & Path & Text1
- SQL = "select [Loan No#] from [" & SheetName & "$A1:DH1048576]"
- Set rst = cnn.Execute(SQL)
- Worksheets("Sheet1").Range("a" & Range("A65536").End(xlUp).Row + 1).CopyFromRecordset rst
-
- rst.Close
- cnn.Close 'Close SQL Connection
- Set rst = Nothing
- Set cnn = Nothing 'Clean SQL from RAM
-
- File.Close True
- Set ExcelApp = Nothing
- Set File = Nothing
-
- End Sub
复制代码 问题已经由大神microyip解决,详见楼下代码。目前该方法适用于行数小于等于65536的xls, xlsx工作表,对于超出65536行的表格,超过部分不会被连接。
|
|