2017-01-16 4 views
1

でエンコードされたCSVファイルをエクスポートする方法:現在、私は、CSVファイルに範囲データをエクスポートするVBAコードを使用して「ユニコード」

Sub Fct_Export_CSV_Migration() Dim Value As String Dim size As Integer 

    Value = ThisWorkbook.Path & "\Export_Migration" & Sheets(1).range("B20").Value & ".csv" chemincsv = Value 

    Worksheets("Correspondance Nv Arborescence").Select Dim Plage As Object, oL As Object, oC As Object, Tmp As String, Sep$ Sep = ";" size = Worksheets("Correspondance Nv Arborescence").range("B" & Rows.Count).End(xlUp).Row Set Plage = ActiveSheet.range("A1:B" & size) 

    Open chemincsv For Output As #1 For Each oL In Plage.Rows 
    Tmp = "" 
    For Each oC In oL.Cells 
     Tmp = Tmp & CStr(oC.Text) & Sep 
    Next 


'take one less than length of the string number of characters from left, that would eliminate the trailing semicolon 
    Tmp = Left(Tmp, Len(Tmp) - 1) 

    Print #1, Tmp Next Close 



    MsgBox "OK! Export to " & Value End Sub 

、私は「ユニコード」でエンコードされたCSVをエクスポートしたいと思います。私はSaveAs(xlUnicodeText)のようなVBA関数を使用する必要があると思うが、その使用方法は?

Thxを

+0

http://stackoverflow.com/questions/4221176/excel-to-csv-with-utf8-encoding –

+1

[Excel to CSV with UTF8 encoding]の可能な複製(http://stackoverflow.com/questions/4221176)/excel-to-csv-with-utf8-encoding) – Comintern

答えて

1

のUnicodeのCSVは、箱から出して、Excelでサポートされているファイル形式の一つではありません。つまり、SaveAsメソッドを使用することはできません。 VBAを使用してこの制限を回避することができます。

私のアプローチでは、file system objectが使用されています。この非常に便利なオブジェクトは、ファイルシステムと対話するのに最適です。それを使用するには、リファレンスを追加する必要があります。

  • VBA IDEから[ツール]をクリックします。
  • 参照...
  • Windowsスクリプトホストオブジェクトモデルをリストから選択します。
  • OKを押します。

enter image description here

コード:

' Saves the active sheet as a Unicode CSV. 
Sub SaveAsUnicodeCSV() 
    Dim fso As FileSystemObject  ' Provides access to the file system. 
    Dim ts As TextStream   ' Writes to your text file. 
    Dim r As Range     ' Used to loop over all used rows. 
    Dim c As Range     ' Used to loop over all used columns. 

    ' Use the file system object to write to the file system. 
    ' WARNING: This code will overwrite any existing file with the same name. 
    Set fso = New FileSystemObject 
    Set ts = fso.CreateTextFile("!!YOUR FILE PATH HERE.CSV!!", True, True) 

    ' Read each used row. 
    For Each r In ActiveSheet.UsedRange.Rows 
     ' Read each used column. 
     For Each c In r.Cells 

      ' Write content to file. 
      ts.Write c.Value 
      If c.Column < r.Columns.Count Then ts.Write "," 
     Next 

     ' Add a line break, between rows. 
     If r.Row < ActiveSheet.UsedRange.Count Then ts.Write vbCrLf 
    Next 

    ' Close the file. 
    ts.Close 

    ' Release object variables before they leave scope, to reclaim memory and avoid leaks. 
    Set ts = Nothing 
    Set fso = Nothing 
End Sub 

このコードは、アクティブワークシートの各使用行をループ。各行内で、使用中のすべての列をループします。各セルの内容は、テキストファイルに追加されます。各行の最後に改行が追加されます。

使用する; !!あなたのファイルパスはここに置き換えてください.CSV !!ファイル名はです。

関連する問題