使用适当的列访问查询到Excel表格&行格式

时间:2015-12-08 15:31:14

标签: excel vba excel-vba

我已经有了以正确方式检索数据的查询,这是我的代码。

Sub Main()

Dim sDBPath As String
sDBPath = "C:\Users\ges\Documents\ExploWR.mdb"

Call Query_Access_to_excel(sDBPath, "Explo1", "SELECT eipl.MOD_CODE, eipl.BOM_KEY, eipl.DIF, eipl.PART_NO, eipl.PART_DESC, eipl.QTY_PER_CAR, eipl.INTERIOR_COLOUR, eipl.EXTERIOR_COLOUR, eipl.SOURCE_CODE, eipl.SHOP_CLASS," & _
   " eipl.PART_CLASS, eipl.PROCESS_CODE, eipl.OPERATION_NO, eipl.DESIGN_NOTE_NO, eipl.WIP, eipl.PART_ID_CODE, eipl.ADOPT_DATE_Y2K,eipl.ABOLISH_DATE_Y2K, ipo_Modelos.EIM, ipo_Modelos.DEST, ipo_Modelos.MY " & _
   " FROM eipl, explo, ipo_Modelos" & _
   " WHERE explo.MOD_CODE = eipl.MOD_CODE And explo.MY = ipo_Modelos.MY" & _
   " And explo.PLANT = ipo_Modelos.PLANT And eipl.ADOPT_DATE_Y2K <= explo.ADOP " & _
   " And explo.DEST = ipo_Modelos.DEST And explo.EIM = ipo_Modelos.EIM")

End Sub

Sub Query_Access_to_excel(sBd As String, sHoja As String, sSQL As String)

     On Error GoTo error_handler

     Dim rs As ADODB.Recordset
     Dim conn As String
     Dim Range_Destino As Range  

     Set Range_Destino = ActiveWorkbook.Sheets(sHoja).Cells(6, 1)     
     conn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source= " & sBd & ";"
     Set rs = New ADODB.Recordset
     Call rs.Open(sSQL, conn, adOpenForwardOnly, adLockReadOnly)

     If Not rs.EOF Then

          Range_Destino.Offset(1, 0).CopyFromRecordset rs
          DoEvents

          MsgBox "Import Complete", vbInformation
     Else
          MsgBox "No registers to import", vbInformation
     End If

     If Not rs Is Nothing Then
        If rs.State = adStateOpen Then
            rs.Close
        End If
        Set rs = Nothing
     End If

     If Not Range_Destino Is Nothing Then
        Set Range_Destino = Nothing
     End If

     Exit Sub
error_handler:
     MsgBox Err.Description, vbCritical
End Sub

我想要做的是正确地将数据放在单元格中,就像这样。

enter image description here

我所拥有的是这样的。我想将数据放在正确的单元格中,我说的是要像第一张图像一样正确放置在列中的最后3个字段。我不知道怎么做而不影响我的查询。

enter image description here

1 个答案:

答案 0 :(得分:0)

因此,只要将数据导出到Excel中,您就有几种选择:

SQL do命令: https://msdn.microsoft.com/en-us/library/office/ff844793.aspx

相同的命令,但在VBA中: Using Excel VBA to export data to MS Access table

您可以遍历表并创建一个数组,然后将该数组打印到电子表格中

在excel中获得数据后,您只需查看格式化 - 添加一些过滤器,更改文本对齐等等,您可以使用&#34;记录宏&#34;用于执行这些任务并清理代码。

所以我想澄清一下 - 您的意思是什么?影响您的查询?&#39;