2017-08-07 68 views
-2

我的代碼創建一個Excel從SQL查詢成功文件雖然它需要太多的時間來創建it.How我可以最大限度地減少創建它的時間呢?
代碼如下:寫入Excel中使用VB(多線)

rsAnaforaPr.DoQuery("SELECT * FROM [dbo].[zam_excel]") 
rsAnaforaPr.MoveFirst() 
    hj = False 
    rowCount = 1 
    While rsAnaforaPr.EoF = False 
     shell1 = rsAnaforaPr.Fields.Item("Value1").Value 
     If hj = False Then 
      oExcel = CreateObject("Excel.Application") 
      oExcel.DisplayAlerts = False 
      oBook = oExcel.Workbooks.Add 
      hj = True 
      oBook.SaveAs("C:\Desktop\New folder\excel.xlsx") 
      oBook.Close(True) 
      oExcel.Quit() 
      oExcel = CreateObject("Excel.Application") 
      oExcel.DisplayAlerts = False 
      oBook = oExcel.Workbooks.Open("C:\Desktop\New folder\excel.xlsx")   
      oSheet = oBook.Worksheets("Sheet1") 
      oSheet.Range("A" & rowCount).Value = "Value1" 
      rowCount = rowCount + 1 
      oSheet.Range("A" & rowCount).NumberFormat = "@" 
      oSheet.Range("A" & rowCount).Value = shell1 
     Else 
      oSheet.Range("A" & rowCount).NumberFormat = "@" 
      oSheet.Range("A" & rowCount).Value = shell1      
     End If 
     rowCount = rowCount + 1 
     rsAnaforaPr.MoveNext() 
    End While 
    oBook.Close(True) 
    oExcel.Quit() 
+0

如果在while循環中構建二維數組並將數組寫入電子表格,將會更快地填充該數組。只要寫數組到你想要的數據的左上角單元格,它會寫的一切一下子,而不是通過細胞 – soohoonigan

+0

細胞首先在一個循環記錄閱讀所有。記錄數組中的元素。然後將它們全部寫入Excel中的單個範圍。 – djv

+2

這個問題更適合於[Code Review](http://stackexchange.codereview.com)IMO。 –

回答

0

我使用類似於下面的代碼。
但是,說,我剛纔注意到你VB.NET標籤...它讀成某種原因訪問。
我想這不會爲此工作?有人讓我知道&我會刪除答案。

Sub Test() 
    Dim oXL As Object 
    Dim oWrkBk As Object 
    Dim DB As DAO.Database 
    Dim qdf As DAO.QueryDef 
    Dim prm As DAO.Parameter 
    Dim rst As DAO.Recordset 

    ''''''''''''''''''''''''''''''''''''''''''''''''''''' 
    'Defer error trapping in case Excel is not running. ' 
    ''''''''''''''''''''''''''''''''''''''''''''''''''''' 
    On Error Resume Next 
    Set oXL = GetObject(, "Excel.Application") 

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
    'If an error occurs then create an instance of Excel. ' 
    'Reinstate error handling.       ' 
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
    If Err.Number <> 0 Then 
     On Error GoTo -1 
     On Error GoTo ERR_HANDLE 
     Set oXL = CreateObject("Excel.Application") 
    End If 

    Set oWrkBk = oXL.workbooks.Add 

    oXL.Visible = True 

    Set DB = CurrentDb 
    Set qdf = DB.CreateQueryDef("", "SELECT * FROM [dbo].[zam_excel]") 
    For Each prm In qdf.Parameters 
     prm.Value = Eval(prm.Name) 
    Next prm 
    Set rst = qdf.OpenRecordset 

    If Not (rst.BOF And rst.EOF) Then 
     oWrkBk.worksheets(1).range("A1").CopyFromRecordSet rst 
    End If 

EXIT_PROC: 

     On Error GoTo 0 
     Exit Sub 

ERR_HANDLE: 
     Select Case Err.Number 

      Case Else 
       MsgBox Err.Description & "(" & Err.Number & ")", vbOKOnly 
       Resume EXIT_PROC 
     End Select 

End Sub