[英]VBA: Create a csv from an excel file xlsm/xlsx
I'm using a code below to change an xlsm file into a csv. The goal is to concatenate the columns cells in the first column for each row: So it works in a certain way but for some rows, the final csv doesn't concatenate all the cells for the same row, I have 2 columns filled instead of only the first.我正在使用下面的代码将 xlsm 文件更改为 csv。目标是连接每一行第一列中的列单元格:所以它以某种方式工作,但对于某些行,最终的 csv 没有连接同一行的所有单元格,我填充了 2 列而不是第一列。 Does anybody have another algo that concatenate each cells for the same row into the first cell and separate them by a ";"
有没有人有另一个算法将同一行的每个单元格连接到第一个单元格中并用“;”分隔它们even if there is some text with comma into certain cells at first?
即使一开始某些单元格中有一些带逗号的文本?
example of a cell:单元格示例:
ID Provider Rationale
4 mister provider the rationale describe an id, and there is some comma in it.
Example of expected output:预期 output 的示例:
id;Provider;Rationale
4;mister provider;therationale describe an id; and there is some comma in it
Dim Fe As Worksheet
Dim Plage As Range
Dim Cel As Range
Dim Tbl() As String
Dim Ligne As String
Dim Dossier As String
Dim Chemin As String
Dim Fichier As String
Dim i As Long
Dim j As Long
Dossier = "C:\my_path"
Fichier = "My_Name " & Format(Now, "dd-mm-yyyy") & ".csv"
'full path
Chemin = Dossier & Fichier
Set Fe = Worksheets("Upload")
Set Plage = DefPlage(Fe, 1, 1)
For i = 1 To Plage.Rows.Count
For j = 1 To Plage.Columns.Count: Ligne = Ligne & Plage(i, j).Value & ",": Next j
'delete the ; at the end
Ligne = Left(Ligne, Len(Ligne) - 1)
'store in a table
ReDim Preserve Tbl(1 To i)
Tbl(i) = Ligne
'For the next on
Ligne = ""
Next i
'create .csv file
Open Chemin For Output As #1
For i = 1 To UBound(Tbl): Print #1, Tbl(i): Next i
Close #1
Function DefPlage(Fe As Worksheet, L As Long, C As Long) As Range
On Error GoTo Fin
With Fe
Set DefPlage = .Range(.Cells(L, C), _
.Cells(.Cells.Find("*", .[A1], -4123, , _
1, 2).Row, .Cells.Find("*", .[A1], -4123, , _
2, 2).Column))
End With
Exit Function
Fin:
Set DefPlage = Nothing
End Function
The problem is that the text has a separator, in this case is the “,”.问题是文本有一个分隔符,在本例中是“,”。 You must put some escape char to not count as a separator.
您必须放置一些转义字符才能不算作分隔符。 If the csv will be open with excel, put all text between quotation marks (“).
如果 csv 将以 excel 打开,请将所有文本放在引号 (") 之间。
Example, change the line that concatenates the string:例如,更改连接字符串的行:
For j = 1 To Plage.Columns.Count: Ligne = Ligne & """" & Plage(i, j).Value & """;": Next j
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.