简体   繁体   中英

ADODB recordset SQL returns error in Excel VBA

The following code produces an error (Method 'Open' of object'_Recordset' failed) when I get to the statement that tries to open the recordset:

Set objClubSalesSourceConn = CreateObject("ADODB.COnnection")
objClubSalesSourceConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & strDirectory & ";" & _
          "Extended Properties=""text;HDR=YES;FMT=Delimited"""
Set rsClubOrders = CreateObject("ADODB.Recordset")

strSQL = "SELECT"
strSQL = strSQL & vbCrLf & "    ClubSales.[Order Number] AS OrderNum,"
strSQL = strSQL & vbCrLf & "    ClubSales.[Submitted Date] AS SaleDate,"
strSQL = strSQL & vbCrLf & "    ClubSales.[Product SKU] AS SKU,"
strSQL = strSQL & vbCrLf & "    ClubSales.[Product Name] AS ItemDesc,"
strSQL = strSQL & vbCrLf & "    ClubSales.[Ext Item Price] AS SaleAmt,"
strSQL = strSQL & vbCrLf & "    ClubSales.[Ext Item Shipping] AS ShipAmt,"
strSQL = strSQL & vbCrLf & "    CASE WHEN ISNULL(ClubSales.[Ship Date])"
strSQL = strSQL & vbCrLf & "        THEN 1"
strSQL = strSQL & vbCrLf & "        ELSE 0 END AS ShipDateNull,"
strSQL = strSQL & vbCrLf & "    ClubSales.[Ship Date] AS ShipDate,"
strSQL = strSQL & vbCrLf & "    ClubSales.[Pickup Date] AS PickupDate,"
strSQL = strSQL & vbCrLf & "    ClubSales.[Quantity Sold] * ClubSales.[Cost Of Goods] AS COGSAmt"
strSQL = strSQL & vbCrLf & "FROM"
strSQL = strSQL & vbCrLf & "    ClubSalesSource.csv AS ClubSales"

rsClubOrders.Open strSQL, objClubSalesSourceConn, adOpenDynamic*

The problem lies in the CASE WHEN statement in the SQL. If I leave that out, the recordset opens okay. I am in Excel VBA, querying a csv file. I need to know how to fix this. I have also unsuccessfully tried using an IIF function like I have done in Access.

strSQL = "SELECT" & _
"    ClubSales.[Order Number] AS OrderNum," & _
"    ClubSales.[Submitted Date] AS SaleDate," & _
"    ClubSales.[Product SKU] AS SKU," & _
"    ClubSales.[Product Name] AS ItemDesc," & _
"    ClubSales.[Ext Item Price] AS SaleAmt," & _
"    ClubSales.[Ext Item Shipping] AS ShipAmt," & _
"    CASE WHEN ISNULL(ClubSales.[Ship Date])" & _
"        THEN 1" & _
"        ELSE 0 END AS ShipDateNull," & _
"    ClubSales.[Ship Date] AS ShipDate," & _
"    ClubSales.[Pickup Date] AS PickupDate," & _
"    ClubSales.[Quantity Sold] * ClubSales.[Cost Of Goods] AS COGSAmt"  & _
" FROM" & _
"    ClubSalesSource.csv AS ClubSales"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM