在Excelmacros中同时写入文件

我正在准备excelmacros从input文件读取数据,并根据条件输出到两个不同的文件。

代码片段如下

fileName1="test1.txt" fileName2="test2.txt" file1 = FreeFile() file2 = FreeFile() Open fileName1 For Output As file1 Open fileName2 For Output As file2 If Condition1=true Then sWrite1="Write to file 1" print #file1,sWrite1 Else sWrite2="Write to file 2" print #file2,sWrite2 End If Close #file1 Close #file2 

预期的输出是“Write to file 1”应该到file1,“Write to file 2”应该是file2。

但是在运行macros后,“写入文件1”和“写入文件2”都写入到file2中,file1是空的。

任何人都可以请帮助我如何同时写入两个文件。

FreeFile()返回可用于打开的下一个文件编号。 当你连续两次调用它时,它会返回相同的值(可能是1),因为你还没有使用文件编号,所以仍然可以打开。

相反,在再次调用FreeFile()之前,您需要使用该文件编号。

更改

 file1 = FreeFile() file2 = FreeFile() Open fileName1 For Output As file1 Open fileName2 For Output As file2 

 file1 = FreeFile() Open fileName1 For Output As file1 file2 = FreeFile() Open fileName2 For Output As file2 

它会按预期工作。

哎呀,这是Excel中的一个错误,而且是可复制的。 我在Open语句中得到了文件已经打开的错误。

尝试切换到使用Microsoft Scripting Runtime库运行同时写入。

 Sub Test2() 'Requires Tools->References->Microsoft Scripting Runtime Dim fso As Scripting.FileSystemObject Set fso = New Scripting.FileSystemObject Dim txtOut(1 To 2) As Scripting.TextStream Set txtOut(1) = fso.CreateTextFile("c:\temp\test1.txt") Set txtOut(2) = fso.CreateTextFile("c:\temp\test2.txt") txtOut(1).WriteLine "Hello 1" txtOut(2).WriteLine "Hello 2" txtOut(1).Close txtOut(2).Close Set txtOut(1) = Nothing Set txtOut(2) = Nothing End Sub