![](/img/trans.png)
[英]Query Excel worksheet in MS-Access VBA (using ADODB recordset)
[英]Splitting ADODB Recordset to Excel worksheet?
我有一個小型的宏程序,可以從SQL到Excel工作表中提取近200萬行數據。 但是問題是,每個工作表最多只能包含1048576行,因此會削減我的數據。
我試圖弄清楚是否有一種方法可以將ADODB Recordset粘貼到Excel之前。
這是我從SQL提取數據到Excel的代碼:
With oRecordSet
.ActiveConnection = oDBConnection
.Source = MySql
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
.Open
End With
Sheets("Data)").Range("A2").CopyFromRecordset oRecordSet
感謝您的幫助。 提前致謝。
您可以查詢數據並應用一些過濾邏輯 。
您可以嘗試delimit ,並管理多達1億行。
您也可以嘗試使用VBA解決方案。
第1步
另存為,擴展名為.xlsm的工作簿(啟用了宏)
第2步
按ALT + F11打開Visual Basic
插入>模塊,然后在右側粘貼下面的代碼(來自Sub
.... End Sub
)
Sub SplitTxt_01()
Const HelperFile As String = "ABCD" '<<< temp. helper text file Name
Const N As Long = 700000 '<<< split each txt in N rows, CHANGE
Dim myPath
myPath = "c:\Folder1\Folder2\" '<<< folder path, CHANGE
Dim myFile
myFile = "Data File.TXT" '<<< your text file. CHANGE txt file name as needed
Dim WB As Workbook, myWB As Workbook
Set myWB = ThisWorkbook
Dim myWS As Worksheet
Dim t As Long, r As Long
Dim myStr
Application.ScreenUpdating = False
'split text file in separate text files
myFile = Dir(myPath & myFile)
Open myPath & myFile For Input As #1
t = 1
r = 1
Do While Not EOF(1)
Line Input #1, myStr
If r > N Then
t = t + 1
r = 1
End If
Open myPath & HelperFile & t & ".txt" For Append As #2
Print #2, myStr
Close #2
r = r + 1
Loop
Close #1
'copy txt files in separate sheets
For i = t To 1 Step -1
Workbooks.OpenText Filename:=myPath & HelperFile & i & ".txt", DataType:=xlDelimited, Tab:=True
Set WB = ActiveWorkbook
Set rng = ActiveSheet.UsedRange
Set myWS = myWB.Sheets.Add
myWS.Name = HelperFile & i
rng.Copy myWS.Cells(1, 1)
WB.Close False
Next
myWB.Save
'Delete helper txt files
Set Fso = CreateObject("Scripting.FileSystemObject")
Set Fldr = Fso.GetFolder(myPath)
For Each Filename In Fldr.Files
If Filename Like "*" & HelperFile & "*" Then Filename.Delete
Next
Application.ScreenUpdating = True
End Sub
作為最后的想法,我會說是時候升級到Python或R了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.