将数据从Excel写入文本文件

时间:2016-04-11 14:17:33

标签: database excel vba excel-vba text-files

           K               L           M
    1    Starting_Year    Code        ID
        ------------------------------------
    2    1982            ALLRIN     400200583
    3    1983            ALLRIN     000083522
    4    1983            ALLRIN     400200583

任何方式创建两个文本文件,根据“Starting_Year”,名称将为“1982”,“1983”,“1982”文件包含“400200583”,“1983”文件包含“000083522”和“ 400200583" 。

这是我必须尝试的,我想知道我是否必须使用for循环来捕获“Starting_Year”,“ID”中的数据?有什么想法,我怎么做?非常感谢!

 Public Function CreateTextFile(FileName As String, Optional Overwrite As Boolean = True, Optional Unicode As Boolean = False) As Scripting.TextStream

    Dim oTs as Scripting.TextStream
    set oTs = CreateTextFile("W:\starting_Year.txt",True)
    oTs.Write("ID")
    oTs.close

    End Function

1 个答案:

答案 0 :(得分:1)

Sub CreateTextFile()     昏暗的ifree,iyear,i,j As Long     Dim ipath As String

ipath = "C:\Users\You" 'TO UPDATE

ifree = FreeFile
i = 2
While Cells(i, 1) <> ""

    iyear = Cells(i, 1)
    ifree = FreeFile
    Open ipath & "\" & iyear & ".txt" For Output As ifree

        j = 2
        While Cells(j, 1) <> ""
            If Cells(j, 1) = iyear Then Print #ifree, Cells(j, 3)
            j = j + 1
        Wend
    Close ifree

i = i + 1
Wend
End Sub

使用Col A中的starting_year,Col B中的Code,Col C中的ID。