我有很多csv文件,我想在VBA宏中批量编辑(Excel2010)。它们用逗号分隔,每个值也有"“左右。这是一个示例输入:
"text","9","01/01/2020"
编辑后,此格式不能更改,因为其他程序依赖它看起来像那样。假设我在excel中打开文件,将9更改为8,然后保存。excel保存的输出将删除“”,如下所示:
text,8,01/01/2020
我试着导入到excel中,但不计入“作为文本限定符,但保存之后,结果看起来像这样
"""text""","""8""","""01/01/2020"""
我尝试过通过文本导入向导将值强制为文本,但没有帮助。
那么,有没有办法在excel中编辑csv文件,同时保持单一的“保存后的格式?
到目前为止,我能想到的最好的解决办法是用记事本之类的东西打开“输出,并对”和“”进行查找和替换,但我发现这有点难以自动化。
发布于 2020-05-12 01:20:22
请尝试下一个代码。它打开不带引号的.csv文件并用引号保存(而不是使用Excel的另存为对话框)。在这两者之间,你可以做任何你需要的修改。csv文件使用初始全名保存,但在末尾添加'_bis`。我这样做只是出于测试的原因。如果它将显示像在我的电脑,你可以关闭csv,并保存它与您的修改和报价,也…请使用记事本打开创建的csv文件。
当然,在以这种方式测试之后,您只能使用添加引号并将数组另存为csv的部分。如果需要,我可以创建一个函数。采用类似的参数,活动表使用范围数组和要保存的csv的完整路径。
Sub OpenTextNoQuotesSaveWithQuotes()
Dim csvFullName As String, arr As Variant, arr1 As Variant
csvFullName = "csvFileFullPath" 'use here your csv file full path
Workbooks.OpenText Filename:=csvFullName, Origin:= _
437, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, Comma:=True
'do whatewer modifications needed here...
'......................................
'add doublequotes:
Set sh = ActiveWorkbook.Sheets(1): arr = sh.UsedRange.Value
ReDim arr1(UBound(arr, 1) - 1, UBound(arr, 2) - 1)
For i = 1 To UBound(arr, 1)
For j = 0 To UBound(arr, 2) - 1
arr1(i - 1, j) = Chr(34) & arr(i, j + 1) & Chr(34)
Next
Next i
'create .CSV comma delimited
Dim newF As String, FileNum, strRow As String
newF = Left(csvFullName, Len(csvFullName) - 4) & "_bis.csv"
FileNum = FreeFile()
Open newF For Output As #FileNum
For i = 0 To UBound(arr1, 1)
For j = 0 To UBound(arr1, 2)
strRow = strRow & arr1(i, j) & "," ' arr1(i, 0) & "," & arr1(i, 1) & "," & arr1(i, 2) & _
arr1(i, 3) & "," & arr1(i, 4)
Next j
strRow = Left(strRow, Len(strRow) - 1)
Print #FileNum, strRow: strRow = ""
Next i
Close #FileNum
End Sub
https://stackoverflow.com/questions/61734355
复制相似问题