将记录拆分为具有相同记录数的txt文件

问题描述 投票:0回答:1

今天我需要你的帮助! 在 Access 数据库中,表 XY 的第一列将使用 VBA 代码写入多个 txt 文件。 txt 文件应至少包含500 条数据记录。如果有剩余,则应均匀分布在 txt 文件中。 示例: 表XY中有1.729条数据记录 结果: 文件576条数据记录 文件576条数据记录 归档577条数据记录

我在www 上没有找到任何东西。 ChatGPT 不明白我的意思,所以我需要你的帮助。

聊天GPT: 这个版本将余数放在最后一个txt文件中...

Sub ExportToTxtFiles_5()
    Dim db As DAO.Database
    Dim rs As DAO.Recordset
    Dim totalRecords As Long
    Dim recordsPerFile As Long
    Dim numFiles As Integer
    Dim i As Integer
    Dim j As Integer
    Dim fileNum As Integer
    Dim filePath As String
    
    ' Set the path where you want to save the text files
    filePath = "C:\Temp\"

    ' Open the database and recordset
    Set db = CurrentDb()
    Set rs = db.OpenRecordset("SELECT Field FROM tableXY")
    rs.MoveLast
    ' Get the total number of records in the table
    totalRecords = rs.recordCount
    
    ' Calculate the number of files needed and the number of records per file
    numFiles = Int(totalRecords / 500) ' Number of files with 500 records
    recordsPerFile = Int(totalRecords / numFiles) ' Records per file
    rs.MoveFirst
    ' Loop through each file
    For i = 1 To numFiles
        ' Open a new text file
        fileNum = FreeFile
        Open filePath & "File_" & i & ".txt" For Output As fileNum
        
        ' Write records to the text file
        For j = 1 To recordsPerFile
            If Not rs.EOF Then
                Print #fileNum, rs.Fields(0) ' Assuming the first column is what you want to export
                rs.MoveNext
            End If
        Next j
        
        ' Close the text file
        Close fileNum
    Next i
    
    ' If there are remaining records, create another file for them
    If Not rs.EOF Then
        fileNum = FreeFile
        Open filePath & "File_" & numFiles & ".txt" For Append As fileNum
        
        ' Write remaining records to the text file
        Do Until rs.EOF
            Print #fileNum, rs.Fields(0) ' Assuming the first column is what you want to export
            rs.MoveNext
        Loop
        
        ' Close the text file
        Close fileNum
    End If
    
    ' Close the recordset and database
    rs.Close
    Set rs = Nothing
    Set db = Nothing
    
    MsgBox "Export completed successfully.", vbInformation
End Sub

vba file ms-access export
1个回答
-1
投票

使用 BitLocker 加密整个驱动器是否可以安全擦除驱动器? 关于“部分否定”的问题 主祷文是典型的一世纪犹太祈祷吗? ARP 表可以存储其他网络的地址吗? 约束下有理数的生成 问题提要

© www.soinside.com 2019 - 2024. All rights reserved.