|
目的:
从Access中复制数据到Excel中,
并设置单元格字体格式
(同一个单元格中部分字符,不同字体,本例中是单元格中第7,第8两个字体设为7号楷体)
如果直接在Access中操作,需要8秒中(仅设置格式部分),
而同样(几乎一致)的代码,在Excel中运行,则只需1秒,甚至不到1秒.
我想Access中的代码应该是写的不合理,
大家指点一下,如何优化代码?
Excel中的代码(只需1秒)
- Private Sub CommandButton1_Click()
- Dim R As Long, C As Long, I As Long, J As Long
- Dim t As Date
- t = Now
- R = Rcount
- C = Ccount
- Application.ScreenUpdating = False
- For I = 4 To R
- For J = 1 To C
- With Sheets("A").Cells(I, J).Characters(7, 2).Font
- .Name = "楷体"
- .FontStyle = "常规"
- .Size = 6
- End With
- Next
- Next
- Application.ScreenUpdating = True
- t = t - Now
- MsgBox t
- End Sub
复制代码
Access中的代码(需要8秒-10秒)
- Private Sub Command0_Click()
- Dim XLA As New Excel.Application
- Dim rs As New ADODB.Recordset
- Dim XLB As Workbook
- Dim XLS As Worksheet
- Dim I As Integer, J As Integer
- Dim R As Long, C As Long
- Dim t As Date
- Set XLB = Nothing
- Set XLS = Nothing
- Set XLB = XLA.Workbooks().Open(CurrentProject.Path & "\Try.xlsb", , True)
- XLB.SaveAs CurrentProject.Path & "" & Format(Now, "yyyy-mm-dd hh nn ss") & ".xlsb" '另存为不同的文件名"
- '---------------
- '导出Excel
- '---------------
- rs.Open "B", CurrentProject.Connection, adOpenKeyset, adLockReadOnly
- Set XLS = XLB.Worksheets("A")
- XLS.Activate
- For I = 0 To rs.Fields.Count - 1
- XLS.Cells(3, 1 + I) = rs.Fields(I).Name
- Next
- XLS.Range("A4").CopyFromRecordset rs
- XLS.Range(XLS.Cells(3, 1), XLS.Cells(rs.RecordCount + 3, rs.Fields.Count)).Borders.LineStyle = xlContinuous
- R = rs.RecordCount + 3
- C = rs.Fields.Count
- rs.Close
- t = Now
- XLA.ScreenUpdating = False
- For I = 4 To R
- For J = 1 To C
- With XLS.Cells(I, J).Characters(7, 2).Font
- .Name = "楷体"
- .FontStyle = "常规"
- .Size = 7
- End With
- Next
- Next
- XLA.ScreenUpdating = True
- t = t - Now
- MsgBox t
- XLB.Save
- XLA.Visible = True
- XLA.WindowState = xlMaximized
- Set rs = Nothing
- Set XLS = Nothing
- Set XLB = Nothing
- Set XLA = Nothing
- End Sub
复制代码 另外以前感觉Excel打开并在屏幕上可见才需要XLA.ScreenUpdating = False
现在发现,即便Excel在内存里打开,并没有显示在屏幕上,如果不加XLA.ScreenUpdating = False
更慢,而且是非常慢,大家可以试试.
附上附件,请大家帮忙优化优化.
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
|