Access VBA를 사용하여 쿼리 결과를 여러 파일로 내보내는 방법

지금 공유 :

Microsoft Access에서 정보를 내보내는 것은 매우 쉽습니다. 단일 내보내기 파일 만 생성하고 싶다고 가정하면됩니다. 그러나 쿼리 (또는 테이블)를 여러 내보내기 파일로 분할해야하는 경우 어떻게합니까? 예를 들어 매월 고객 거래 목록을 내 보내야하는 경우 각 고객이 자신의 내보내기 파일을 가지고 있습니까? 이 기사가 도움이 될 수 있습니다. 2, 10 또는 XNUMX 개의 다른 내보내기 내보내기를 생성하는 것은 약간의 VBA 코드 스 니펫을 실행하는 것만 큼 간단하며 작업은 수동으로 자르기 / 붙여 넣기가 아닌 몇 초 만에 완료됩니다. 그럼 시작하겠습니다 ...

접근

가능한 한 유연하고 유용하기를 원하기 때문에이 기사의 코드는 평소보다 약간 길어질 것이지만 그 이유는 곧 알게 될 것입니다.

먼저, 우리가 달성하고자하는 바를 요약 해 보겠습니다.

쿼리가 주어지면 지정된 필드의 값이 변경 될 때마다 새 파일을 출력합니다.

난제

Access에서 쿼리 내보내기이렇게하려면 쿼리 결과를 단계별로 살펴보고 현재 행의 관련 필드를 이전 행의 값과 비교해야합니다. 다른 경우 새 파일을 만들고 start 거기에 쿼리 결과를 출력합니다.

이것이 적합하지 않은 것

이미 언급했듯이 데이터베이스의 일부를 내보내고 싶은 이유는 많이 있지만 백업 / 아카이브 목적으로 사용하는 것은 그 중 하나가 아닙니다. 여기에서 사용 – 복구에 직면 한 경우 수행 할 마지막 작업 손상된 mdb 데이터베이스 많은 수출품을 다시 연결하는 방법을 찾고 있습니다!

해결책?

고양이 피부를 만드는 방법은 항상 많습니다.이 방법은 하나 일뿐입니다.하지만 제 생각에는 꽤 잘 작동하는 방법이 있습니다. 먼저 우리는 더 쉽게 이동할 수 있도록 쿼리를 배열로 읽어 들일 것입니다. 다음으로 해당 배열을 반복하여 관련 필드에서 새 값을 찾았는지 여부를 확인합니다. 새 값이 아니면 전체 레코드를 작성중인 현재 파일에 출력하고 새 값이면 해당 파일을 닫고 star새로운 것.

그리고 코드…

Sub DoExport(fieldName As String, queryName As String, filePath As String, Optional delim As Variant = vbTab)
    Dim db As Database
    Dim objRecordset As ADODB.Recordset
    Dim qdf As QueryDef
    
    Dim fldcounter, colno, numcols As Integer
    Dim numrows, loopcount As Long
    Dim data, fs, fwriter As Variant
    Dim fldnames(), headerString As String
    
    'get details of the query we'll be exporting
    Set objRecordset = New ADODB.Recordset
    Set db = CurrentDb
    Set qdf = db.QueryDefs(queryName)
    
    'load the query into a recordset so we can work with it
    objRecordset.Open qdf.SQL, CurrentProject.Connection, adOpenDynamic, adLockReadOnly
    
    'load the recordset into an array
    data = objRecordset.GetRows
    
    'close the recordset as we're done with it now
    objRecordset.Close
    
    'get details of the size of array, and position of the field we're checking for in that array
    colno = qdf.Fields(fieldName).OrdinalPosition
    numrows = UBound(data, 2)
    numcols = UBound(data, 1)
    
    
    'as we'll need to write out a header for each file - get the field names for that header
    'and construct a header string
    ReDim fldnames(numcols)
    For fldcounter = 0 To qdf.Fields.Count - 1
        fldnames(fldcounter) = qdf.Fields(fldcounter).Name
    Next
    headerString = Join(fldnames, delim)
    
    'prepare the file scripting interface so we can create and write to our file(s)
    Set fs = CreateObject("Scripting.FileSystemObject")
    
    'loop through our array and output to the file
    For loopcount = 0 To numrows
        If loopcount > 0 Then
            If data(colno, loopcount) <> data(colno, loopcount - 1) Then
                If Not IsEmpty(fwriter) Then fwriter.Close
                Set fwriter = fs.createTextfile(filePath & data(colno, loopcount) & ".txt", True)
                fwriter.writeline headerString
                writetoFile data, queryName, fwriter, loopcount, numcols
            Else
                writetoFile data, delim, fwriter, loopcount, numcols
            End If
        Else
            Set fwriter = fs.createTextfile(filePath & data(colno, loopcount) & ".txt", True)
            fwriter.writeline headerString
            writetoFile data, delim, fwriter, loopcount, numcols
        End If
    Next
    
    'tidy up after ourselves
    fwriter.Close
    Set fwriter = Nothing
    Set objRecordset = Nothing
    Set db = Nothing
    Set qdf = Nothing

End Sub


'parameters are passed "by reference" to prevent moving potentially large objects around in memory
Sub writetoFile(ByRef data As Variant, ByVal delim As Variant, ByRef fwriter As Variant, ByVal counter As Long, ByVal numcols As Integer)
    Dim loopcount As Integer
    Dim outstr As String
    
    For loopcount = 0 To numcols
        outstr = outstr & data(loopcount, counter)
        If loopcount < numcols Then outstr = outstr & delim
    Next
    fwriter.writeline outstr
End Sub

코드의 기능 – 핵심 사항

VBA 액세스m의 코드에 주석을 추가했습니다.ost 하지만 강조 할 가치가있는 몇 가지 사항이 여전히 있습니다.

첫째 – 코드를 두 개의 루틴으로 분할했습니다. 첫 번째는 현재 레코드가 현재 작업중인 파일에 기록되어야하는지 또는 새 파일에 기록되어야하는지 여부를 확인합니다. 두 번째 루틴은 전체 레코드에 대한 세부 사항을 파일로 출력합니다. 코드의 중복을 줄이기 위해 이런 식으로 수행되었습니다. 그렇지 않으면 여러 곳에서 동일한 루프가 발생하는 것을 볼 수 있습니다.

둘째 – 저는 "쿼리 정의"를 사용하여 작업중인 쿼리에 대한 세부 정보를 얻습니다. 테이블 작업에이를 적용 할 수 있도록하려면 "쿼리 정의"를 사용하도록 스왑하는 방법을 살펴 봅니다. 대신 테이블 정의”를 참조하십시오.

즉, 이것은 당신이 다시 참조하고 많이 사용하게 될 약간의 코드라고 확신합니다!

저자 소개 :

Mitchell Pond는 데이터 복구 전문가입니다. DataNumen, Inc.는 다음과 같은 데이터 복구 기술 분야의 세계적 리더입니다. 수리 SQL Server 데이터 그리고 엑셀 복구 소프트웨어 제품. 자세한 내용은 WWW.datanumen.COM

지금 공유 :

댓글이 닫혀있다.