【问题标题】:Writing to the files simultaneously in Excel Macro在 Excel 宏中同时写入文件
【发布时间】:2016-06-01 19:51:22
【问题描述】:

我正在准备 excel 宏以从输入文件中读取数据并根据条件将其输出到两个不同的文件中。

代码片段如下

   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

预期的输出是“写入文件 1”应该转到文件 1 而“写入文件 2”应该是文件 2。

但是在运行宏之后, “写入文件 1”和“写入文件 2”都写入文件 2 file1 为空。

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

【问题讨论】:

  • 仔细查看您的线路Open fileName 1 For Output as file1,在此之下,您又看到了Open fileName1,所以这可能会导致问题?

标签: vba excel macros


【解决方案1】:

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

它会按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2012-01-08
    • 1970-01-01
    相关资源
    最近更新 更多