我目前正在使用 VBA 来运行存储过程和已提取到表中的存储数据。然后,VBA会相应地查询数据中的所有数据,并将其放入excel中。
这里的问题是,VBA 需要很长时间才能将所有数据(大约 100k 行数据)提取到 excel 中。有没有其他方法可以加快这个过程?以下是我的代码的一部分。粗体字是插入到 excel 代码中。
'Row number where data inserting starts
Do
current_sheet = owb.ActiveSheet
With current_sheet
'Insert header to worksheet in first row, ie. A1, B1, C1
For i = 0 To data_cols.GetLength(0) - 1
cell = data_cols(i, 0) & header_row_num 'Change to header_row_num
.Range(cell).Value = data_cols(i, 1)
Next i
End With
row_count = header_row_num + 1 'Change the first row count to a row after header_row_num
'Insert data to worksheet
While rs.EOF = False
With current_sheet
'Set format of specic columns before inserting data
.Columns("A").NumberFormat = "@"
.Columns("B").NumberFormat = "@"
.Columns("C").NumberFormat = "@"
.Columns("D").NumberFormat = "@"
.Columns("E").NumberFormat = "@"
.Columns("F").NumberFormat = "@"
.Columns("G").NumberFormat = "@"
.Columns("H").NumberFormat = "@"
.Columns("I").NumberFormat = "@"
.Columns("J").NumberFormat = "@"
.Columns("K").NumberFormat = "@"
.Columns("L").NumberFormat = "@"
.Columns("M").NumberFormat = "@"
.Columns("N").NumberFormat = "@"
.Columns("O").NumberFormat = "@"
.Columns("P").NumberFormat = "@"
.Columns("Q").NumberFormat = "@"
.Columns("R").NumberFormat = "@"
.Columns("S").NumberFormat = "@"
**'Start inserting data
For i = 0 To data_cols.GetLength(0) - 1
'Get the cell name
cell = data_cols(i, 0) & row_count
'Populate data to the cell
If IsDBNull(rs.Fields(data_cols(i, 2)).Value()) Then
.Range(cell).Value = " "
Else
.Range(cell).Value = rs.Fields(data_cols(i, 2)).Value()
End If
Next i
End With
rs.MoveNext()
'Indicates next row
row_count += 1**
If row_count > 60000 Then
owb.Worksheets.Add(, current_sheet)
need_new_sheet = True
Console.WriteLine("Added new sheet to workbook...")
Exit While
Else
need_new_sheet = False
End If
End While
Loop While (need_new_sheet And rs.EOF = False)
如果您需要知道某些变量。
row_count = header_row_num + 1 'Change the first row count to a row after header_row_num
oxl = CreateObject("Excel.Application")
oxl.Visible = False
owb = oxl.Workbooks.Add
Dim data_cols(,) As String = {{"A", "Name", "NAME"}, _
{"B", "Age", "AGE"}} (Not real columns, example)
任何建议或想法将不胜感激。提前致谢 :)