Create CSV file from Excel data for an each distinct value in a column?

大兔子大兔子 提交于 2020-01-07 05:04:28

问题


I have an excel with vendor codes(NUMBERS) as one of the columns.

VENDORITEM|  DESCRIPTION  |PRICE|PRICEGROUP|VENDOR NUMBER|PRODUCT CATEGORY
_______________________________
HNM36789  |30ML FLUID CLIN|50.00|    B     |  023445     |CMI

TNG78934  |BACK PAD 3X5"  |32.00|    D     |  000905     |CMI

JPD12780  |FLEX DRILL GH  |9.50 |    R     |  233590     |MISC

I need to create an excel vba macro so that I can export the data for each vendor number into a csv file and give the csv filename something like 023445NEW, and specify a folder to save all the csv files ? Currently, I doing this manually and taking lot of time.


回答1:


This convert range to csv.

Sub SaveRangeToCsvFiles()
    Dim FileName As String
    Dim Ws As Worksheet
    Dim rngDB As Range
    Dim r As Long, c As Long
    Dim pathOut As String
    Dim i As Long

    pathOut = ThisWorkbook.Path & "\" '<~~ set your path:  C:\temp\

    Set Ws = ActiveSheet 'Sheets("AllData")
    With Ws
        r = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
        'c = .Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
        For i = 2 To r
            Set rngDB = .Range("a" & i).Resize(1, 6)
            FileName = .Range("a" & i).Offset(, 4) & "NEW"
            TransToCSV pathOut & FileName & ".csv", rngDB
        Next i
    End With
    MsgBox ("Files Saved Successfully")
End Sub
Sub TransToCSV(myfile As String, rng As Range)

    Dim vDB, vR() As String, vTxt()
    Dim i As Long, n As Long, j As Integer
    Dim objStream
    Dim strTxt As String

    Set objStream = CreateObject("ADODB.Stream")
    vDB = rng
    For i = 1 To UBound(vDB, 1)
        n = n + 1
        ReDim vR(1 To UBound(vDB, 2))
        For j = 1 To UBound(vDB, 2)
            vR(j) = vDB(i, j)
        Next j
        ReDim Preserve vTxt(1 To n)
        vTxt(n) = Join(vR, ",")
    Next i
    strTxt = Join(vTxt, vbCrLf)
    With objStream
        '.Charset = "utf-8"
        .Open
        .WriteText strTxt
        .SaveToFile myfile, 2
        .Close
    End With
    Set objStream = Nothing

End Sub


来源:https://stackoverflow.com/questions/46589803/create-csv-file-from-excel-data-for-an-each-distinct-value-in-a-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!