2

我创建了一个.txt包含 4 行的文件,其中包含以下几行:

4

1

3

2

然后我使用“Shell”对文件进行排序。结果排序:

1

2

3

4

最后我正在阅读排序文件并将每一行写入第二个文件,但它们以原始顺序出现!

请帮忙。

这是代码:

Option Explicit
Sub my_mac2()
   Dim my_path, my_tmp_file, my_out_file, my_data_from_tmp, my_command As String
   Dim my_tmp_file_num, my_out_file_num As Integer
   my_path = "E:\MASAV\VBA\"
   my_tmp_file = my_path & "_tmp.txt"
   my_out_file = my_path & "_out.txt"
   my_tmp_file_num = FreeFile()
   Open my_tmp_file For Output As #my_tmp_file_num
   Print #my_tmp_file_num, "4"
   Print #my_tmp_file_num, "1"
   Print #my_tmp_file_num, "3"
   Print #my_tmp_file_num, "2"
   Close #my_tmp_file_num
   my_command = "sort " & my_path & "_tmp.txt /O " & my_path & "_tmp.txt"
   Shell my_command, vbHide
   my_tmp_file_num = FreeFile()
   Open my_tmp_file For Input As #my_tmp_file_num
   my_out_file_num = FreeFile()
   Open my_out_file For Output As #my_out_file_num
   While Not EOF(my_tmp_file_num)
       Line Input #my_tmp_file_num, my_data_from_tmp
       Print #my_out_file_num, my_data_from_tmp
   Wend
   Close #my_tmp_file_num
   Close #my_out_file_num
End Sub
4

1 回答 1

1

当你执行sort命令时,命令行是从生成的

my_command = "sort " & my_path & "_tmp.txt /O " & my_path & "_tmp.txt"

换句话说 - 您正在使用输入文件作为输出文件,我怀疑这不是一个好主意。那是你打算做的吗?

您之前确实声明了两个不同的文件名;

my_tmp_file = my_path & "_tmp.txt"
my_out_file = my_path & "_out.txt"

那你为什么不把这条线改成

my_command = "sort " & my_tmp_file & " /O " & my_out_file

这会在第二个文件中产生输出,并使代码的后续部分变得不必要。如果您希望第一个文件也被排序,您可以将第二个文件复制回第一个文件。

于 2013-05-27T22:49:06.903 回答