从Microsoft Access创建自定义文本文件

时间:2016-01-18 16:37:01

标签: vba ms-access access-vba

我正在尝试从Access数据库创建一个看起来完全像这样的文本文件:

CADWorx P&ID Drop Down List Configuration File.

Notes:

-This file contains information on what
 appears in the drop down list in the
 CEDIT Additional Data Dialog

-Entries should be separated by a semi-colon (;)

-If a value is not set, an edit box will appear
 in the CEDIT Additional Data Dialog instead
 of a drop down list.

-Example: AREA_=031;032;033;034A;034B;
 Example: SERVICE_=AEC;HW;LH;CCH;



[DOCUMENTATION]
TYPE_=
DATESUB_=
DATEAPR_=
CREATEBY_=
APRBY_=


[LINE]
SERVICE_=OIL;FUEL GAS; 
AREA_=
UNIT_=
COUNT_=
TYPE_=
RATING_=
FLGFACE_=
DESIGNPSI_=
DESIGNDEG_=
LINE_NUM_=
OPERPSI_=
OPERDEG_=
SPECPRESS_=
SPECTEMP_=
MINDEG_=
TESTPSI_=
INSULATE_=
HEATTRACE_=
XRAY_=
CODE_=
JOINTEFF_=
WELDPROC_=
INSPECT_=
MATPIPE_=
COMPNOTE_=
NOTE_=
USER1_=

左边的所有字段(以'_ ='结尾)是我数据库中的字段标题。然后,如上所述,必须添加这些字段的值并用分号分隔。我已经研究了一个多星期,而且几乎只是在Access中使用文本文件自定义来达到目的。有人能告诉我这是不是要走了?或者我应该将数据导出到Excel并从那里创建文本文件吗?

非常感谢您的帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

以下是将记录写入文件的基础知识:

Dim dbs As Database
Dim rst As Recordset
Dim intFileDesc As Integer      'File descriptor for output file (number used by OS)
Dim strOutput As String         'Output string for entry
Dim strRecordSource As String   'Source for recordset, can be SQL, table, or saved query
Dim strOutfile As String        'Full path to output file

Kill strOutfile                 'Delete the output file before using it.
                                'Not necessary, but ensures you have a clean copy every time
intFileDesc = FreeFile          'Get a free file descriptor
Open strOutfile For Binary As #intFileDesc 'Open the output file for writing
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset(strRecordSource ) 'open the recordset based on our source string
With rst    'make things easier for ourselves
While Not .EOF
        strOutput = !Field1 & ";" & !Field2 & ";" & !Field3
        Print #intFileDesc, strOutput   'Print output string to file
        .MoveNext       'Advance to next record in recordset
    Wend
    .Close                  'Close this recordset
End With
Close #intFileDesc          'Close output file
Set rst = Nothing
Set dbs = Nothing       'Garbage handling before we exit the function

基本路线是:

Print #intFileDesc, strOutput   'Print output string to file

您可以一次写一行。

因此,构建一个扩展此功能的函数,逐行创建输出(包括间距的空行)直到完成。而已。

需要大量代码,但实际上非常简单。对于像这样的输出,没有其他方法。