從Excel數據中為列中的每個不同值創建CSV文件?

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


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

我有一個excel與供應商代碼(NUMBERS)作為列之一。

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.

我需要創建一個excel vba宏,以便我可以將每個供應商編號的數據導出到csv文件中,並為csv文件名提供類似023445NEW的文件,並指定一個文件夾來保存所有csv文件?目前,我手動執行此操作並花費大量時間。

1 个解决方案

#1


0  

This convert range to csv.

此轉換范圍為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://www.itdaan.com/blog/2017/10/05/72f553fa91116068dd4e7822ab62a563.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com