MS Access VBA导出到TXT ERROR

时间:2012-05-02 09:33:45

标签: ms-access access-vba

我有一个Microsoft Access VBA文件,如下所示。

Sub ExportTextFileDelimited(FileName As String, _
    DataSet As String, _
    Delimiter As String, _
    TextQualifier As String, _
    WithFieldNames As Boolean)
    On Error GoTo ExportTextFile_Err

    Dim cnn As ADODB.Connection
    Dim rst As New ADODB.Recordset

    Dim Directory As String
    Dim MyString As String, strSQL As String
    Dim strDS As String
    Dim I As Integer

    Open FileName For Output As #1
    Set cnn = CurrentProject.Connection

    rst.Open DataSet, cnn, adOpenForwardOnly, adLockReadOnly
    If WithFieldNames Then
        For I = 0 To rst.Fields.Count - 1
            MyString = MyString & TextQualifier & rst(I).Name & TextQualifier & Delimiter
        Next I
        MyString = Left(MyString, Len(MyString) - 1)
        Print #1, MyString
    End If
    rst.MoveFirst
    Do While Not rst.EOF
        MyString = ""
        For I = 0 To rst.Fields.Count - 1
            'check for text datatype (202)
            If rst(I).Type = 202 Then
                MyString = MyString & TextQualifier & _
                rst(I)
            Else
                MyString = MyString & rst(I)
            End If
        Next I
            MyString = Left(MyString, Len(MyString) - 2)
        Print #1, MyString
        rst.MoveNext
    Loop

ExportTextFile_Exit:
    ' Close text file.
    Close #1
    rst.Close
    Set cnn = Nothing
    Exit Sub
ExportTextFile_Err:
    MsgBox Err.Description
    Resume ExportTextFile_Exit
End Sub

此代码工作正常,它输出一个Query.txt文件,其中包含以下数据:

请查看并参考此示例图片。

Example of the problem described below

我的问题是,如何为AMAL和SAMANTHA GAMAGE数据应用最大宽度?

1 个答案:

答案 0 :(得分:1)

这里要求的通常称为“固定宽度”(或“固定长度”),通常被认为是与逗号分隔(或CSV)文件不同的文本文件类型。虽然您可以将两个概念混合在同一个文件中。

要将String值设置为指定长度,您需要使用VBA的空间函数。

Dim s as String
s = "AMAL"
s = s & Space(15 - len(s)) 'Add spaces to end
s = Space(15 - len(s)) & s 'Add spaces to beginning

从你的帖子中不清楚为什么你只在这个字段中添加空格以及你将如何确定该字段的长度(即要添加多少空格)。您的功能实际上未正确设置此功能。有很多种方法可以重新设计此函数,以便知道要添加空格的字段以及要添加到该字段的空格数。您选择哪种方式取决于您的个人需求。

只是为了让您了解如何在函数中使用它:

Dim iMaxLength as Integer
Do While Not rst.EOF
    If Len(rst("UserName").Value) > iMaxLength Then iMaxLength = Len(rst("UserName").Value)
    rst.MoveNext
Loop

Do While Not rst.EOF
    rst.movefirst
    MyString = ""
    For I = 0 To rst.Fields.Count - 1
        'check for text datatype (202)
        If rst(I).Type = 202 Then
            If rst(I).Name = "UserName" Then
                MyString = MyString & TextQualifier & _
                rst(I) & Space(iMaxLength - Len(rst(I))) 
            Else
                MyString = MyString & TextQualifier & _
                rst(I)
            End If
        Else
            MyString = MyString & rst(I)
        End If
    Next I
        MyString = Left(MyString, Len(MyString) - 2)
    Print #1, MyString
    rst.MoveNext
Loop