我需要使用VBA修改CSV文件的帮助。我进行了研究并提出了此解决方案。但是,我无法获得预期的输出。因此,例如,我有一个CSV文件:
ProductID,ProductName,SupplierName,CategoryID,Unit,Price
,,,,,
1,Chais,John Ray,1,10 boxes x 20 bags,18.00093483
2,Chang,Michael,1,24 - 12 oz bottles,19.66890343
我想更改productname
和suppliername
下的所有值。并更改类似ProductID和Column Name的组合。我的预期输出应如下所示:
ProductID,ProductName,SupplierName,CategoryID,Unit,Price
,,,,,
1,1 ProductName,1 SupplierName,1,10 boxes x 20 bags,18.00093483
2,2 ProductName,2 SupplierName,1,24 - 12 oz bottles,19.66890343
它可以发生多次,并且可以更改列的位置。这是我的代码:
Sub test()
Dim FilePath As String, LineFromFile As Variant, LineItems() As String, strFile As Variant
FilePath = "C:\Users\mestrivo\Documents\Files\MyFirstProg\test.csv"
Open FilePath For Input As #1
Do Until EOF(1)
Line Input #1, LineFromFile
LinteItems = Split(LineFromFile, ",")
LineItems(1) = LineItems(0) & " ProductName"
LineItems(2) = LineItems(0) & " SupplierName"
strFile = Join(LineItems, ",")
Loop
Open "C:\Users\mestrivo\Documents\Files\MyFirstProg\test - 2.csv" For Output As #1
Print #1, strFile
Close #1
End Sub
请帮助我检查我的代码。我在这部分上出错:
Open "C:\Users\mestrivo\Documents\Files\MyFirstProg\test - 2.csv" For Output As #1
说文件已经打开。
答案 0 :(得分:2)
从不硬编码文件句柄,它们不是供您使用的,它们是供VBA查询可用的文件句柄并给您的免费,可用文件句柄。使用FreeFile
函数执行此操作。
Dim fileHandle As Long
fileHandle = FreeFile
然后将所有硬编码的#1
句柄替换为#fileHandle
。
您不能使用相同的句柄打开两个不同的文件。您已经打开文件进行输入:
Open FilePath For Input As #1
因此,当您尝试使用相同的句柄进行输出时...
Open "C:\Users\mestrivo\Documents\Files\MyFirstProg\test - 2.csv" For Output As #1
那是您遇到错误的时候;您尚未关闭#1
句柄,现在您正试图重用它来打开另一个文件-您不能这样做。
您要处理两个文件,因此您可以打开第一个文件,先读取它,然后然后将其关闭,然后再打开第二个文件,写入该文件,然后将其关闭-或者,您也可以打开两个,然后在阅读另一个的同时写一个,然后关闭两个。
无论哪种方式,都不应该对文件句柄进行硬编码。使用FreeFile
获取免费文件句柄。总是。
答案 1 :(得分:0)
尝试一下:
Sub test()
Dim FilePath As String, LineFromFile As Variant, _
LineItems() As String, strFile As Variant
FilePath = "mycsv.csv"
Open FilePath For Input As #1
Do Until EOF(1)
Line Input #1, LineFromFile
LineItems() = Split(LineFromFile, ",")
'I suggest to add the following 'If' statements
If LineItems(0) <> "" Then
LineItems(1) = LineItems(0) & " ProductName"
LineItems(2) = LineItems(0) & " SupplierName"
End If
If strFile <> "" Then strFile = strFile & Chr(10)
'-------------------------------------------------
strFile = strFile & Join(LineItems, ",")
Loop
'In the next 'Open' statement you are trying to
'assign an object over another that's already opened,
'therefore you must close the previous object first
'and / or declare the second one with another name
Close #1
Open "mycsv2.csv" For Output As #1
Print #1, strFile
Close #1
End Sub