Create a csv file using text file with excel macro

时间:2018-12-03 12:59:38

标签: excel vba excel-vba

Using a text file which contends in column 3 the value as hour, i would like to create a csv file using an excel macro.

The purpose is to create a csv file ( 3 lines ) which contends.

1 line = minimum and maximum value in column 3
2 line = write in 24 columns ( 0,1,2,3,4,5 ect )
3 line = count values for each hour, if no value is found for specific hour.. then print 0

Input file

123 3 04
122 3 03
122 3 03
122 3 04
122 4 04
122 5 05
122 3 12
122 4 15
122 5 21
122 5 20
122 5 20

Output desired

3,21
0,1,2,3,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,22,23
0,0,0,2,3,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,2,1,0,0

Thanks in advance.

2 个答案:

答案 0 :(得分:1)

尝试

Sub test()
    Dim Path As String, Fn As String
    Dim vDB, vR(), vText1(), vText2()
    Dim wf As WorksheetFunction
    Dim rngDB As Range
    Dim strResult As String
    Dim myMin As Integer, myMax As Integer
    Dim i As Long


    Set rngDB = Range("c1", Range("c" & Rows.Count).End(xlUp))
    Set wf = WorksheetFunction

    vDB = Range("a1").CurrentRegion


    ReDim vR(1 To 3)

    myMin = wf.Min(rngDB)
    myMax = wf.Max(rngDB)
    vR(1) = myMin & "," & myMax
    ReDim vText1(23): ReDim vText2(23)
    For i = 0 To 23
        vText1(i) = i
        vText2(i) = wf.CountIf(rngDB, i)
    Next i
    vR(2) = Join(vText1, ",")
    vR(3) = Join(vText2, ",")
    strResult = Join(vR, vbCrLf)

    Path = ThisWorkbook.Path & "\"
    Fn = "test1.csv"
    Fn = Path & Fn
    TransToCsv strResult, Fn
End Sub
Sub TransToCsv(strTxt As String, strFile As String)
    Dim objStream As Object
    Set objStream = CreateObject("ADODB.Stream")

    With objStream
        '.Charset = "utf-8"
        .Open
        .WriteText strTxt
        .SaveToFile strFile, 2
        .Close
    End With
    Set objStream = Nothing

End Sub

答案 1 :(得分:0)

我使用以下宏获得了所需的输出,

zsh