VBA SQL内连接查询结果列错位问题求助
VBA导出INNER JOIN查询结果时列错位问题
我编写了名为FindDoubleBookings的VBA子程序,通过ADODB连接当前Excel文件,执行包含INNER JOIN的SQL语句,关联Inbounds和Outbounds两个工作表的数据,并将结果输出至DoubleBookings工作表。目前查询能获取正确的数据,但输出时部分内容显示在工作表的非预期区域;添加表头代码前功能正常,其他4个同类功能的工作表运行无异常,仅该使用INNER JOIN的查询出现列错位问题(如图所示)。
子程序代码
Sub FindDoubleBookings() Dim conn As New ADODB.connection Dim rng As Excel.Range conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & _ ";Extended Properties=""Excel 12.0;HDR=YES;"";;" Dim doubleQuery As String With Sheets("Inbounds") Dim dataRef As String dataRef = Intersect(.UsedRange, .Range("8:" & .Rows.Count)).Address(0, 0) doubleQuery = "Select [vrid],[route],[schedule_date],[vehicle_carrier],[carrier_name],[orig_planned_yard_checkin_time],[orig_planned_yard_checkout_time],[dest_node]from [Inbounds$" & dataRef & "] AS Delivery INNER JOIN [Outbounds$" & dataRef & "] AS Collection on Delivery.actual_vehicle = Collection.actual_vehicle where Delivery.[orig_planned_yard_checkin_time] <= Collection.[orig_planned_yard_checkout_time] order by [Delivery.Route]" End With Dim drs As New ADODB.Recordset drs.Open doubleQuery, conn Dim wSht As Worksheet Set wSht = ThisWorkbook.Worksheets("DoubleBookings") With wSht .Cells.clearContents For i = 0 To drs.Fields.Count - 1 .Cells(8, i + 1).Value = drs.Fields(i).Name Next i .Range("A9").CopyFromRecordset drs End With ThisWorkbook.Sheets("DoubleBookings").Activate conn.Close End Sub
问题表现截图

内容的提问来源于stack exchange,提问作者F.OLeary
相关产品推荐
相关产品推荐

