简体   繁体   中英

excel vba - sort txt file in shell

I have created a .txt file with 4 lines which contains the following lines:

4

1

3

2

I then use "Shell" to sort the file. The result is sorted:

1

2

3

4

Finally I am reading the sorted file and write each line into a second file, but they come out at the original order!

Please help.

Here is the code:

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

When you execute the sort command, the command line is generated from

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

In other words - you are using the input file as the output file, and I suspect that's not a good idea. Is that what you intended to do?

You did declare two different file names earlier;

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

so why don't your change this line to

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

This produces output in the second file, and makes the subsequent part of the code unnecessary. If you want the first file to be also sorted, you can copy the second back into the first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM