我创建了一个包含4行的.txt
文件,其中包含以下几行:
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
答案 0 :(得分: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
这会在第二个文件中生成输出,并且不需要后续部分代码。如果您希望对第一个文件进行排序,则可以将第二个文件复制回第一个文件。