Tuesday, November 21, 2017

XLSX excel vba connectionstring

Sub test()

Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=C:\temp\JW_E&PM_04.xlsx;" & _
"Extended Properties=Excel 8.0;"
.Open
End With
End Sub


Sub ShowRecordCount()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
With cn
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .ConnectionString = "Data Source=C:\temp\JW_E&PM_04.xlsx;" & _
"Extended Properties=Excel 12.0;"
    .Open
End With

sSQL = "SELECT * FROM [sheet1$]"
Set oRs = New ADODB.Recordset
oRs.Open sSQL, cn, adOpenStatic, _
               adLockBatchOptimistic, adCmdText
MsgBox oRs.RecordCount
cn.Close
End Sub


read named range in VBA


Sub ShowRecordCount()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
With cn
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .ConnectionString = "Data Source=C:\temp\JW_E&PM_04.xlsx;" & _
"Extended Properties=Excel 12.0;"
    .Open
End With

sSQL = "SELECT * FROM testrange"
'sSQL = "SELECT * FROM [Sheet1$A1:E46]"
Set oRs = New ADODB.Recordset
oRs.Open sSQL, cn, adOpenStatic, _
               adLockBatchOptimistic, adCmdText
MsgBox oRs.RecordCount
cn.Close
End Sub

No comments: