1

i would like to Sort an array in vbs, so the numbers which are contained in the array are ascending. I'm reading the numbers from a text file

    Sub Main()
Dim Werte(10)
Dim c  
Dim fso  
Set fso = CreateObject("Scripting.FileSystemObject")  
Set c = fso.Drives  
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("Y:\Benutzer\Desktop\Werte.txt",1)
Dim strLine
Dim i
i=0
do while not objFileToRead.AtEndOfStream
    strLine = objFileToRead.ReadLine()
    Werte(i)=strLine
    i=i+1
loop
objFileToRead.Close
Set objFileToRead = Nothing

for x=LBound(Werte) To UBound(Werte) - 1 Step 1
    for j= 0 to UBound(Werte)-1
        if Werte(j)>Werte(j+1) then
            temp=Werte(j+1)
            Werte(j+1)=Werte(j)
            Werte(j)=temp
        end if
    next
next 

PATH="Y:\Benutzer\Desktop\Werte_sortiert.txt"
Array_ToTextFile Werte,PATH
End Sub

Function Array_ToTextFile(a,path)  

    Const ForWriting = 2  

    Dim fso  

    Dim writer  

    Dim i  

    Set fso = CreateObject("Scripting.FileSystemObject")  

    Set writer = fso.OpenTextFile(path,ForWriting,True)  

    For i = lbound(a) to ubound(a)  
        writer.writeline a(i)  
    Next  

    writer.close  
End Function  
Main

Text file looks like this:

10 9 8 7 6 5 4 3 2 1 0

Result looks like this:

0 1 10 2 3 4 5 6 7 8 9

The number 10 should be at the end, but is at the 3rd position after sorting. I would appreciate your help.

1
  • 2
    Although this is answered, I just wanted to add that you really don't need to read each line. You can read the entire file upfront and then Split the data on vbCrLf delim. Or you can use System.Collections.ArrayList and add each line into sorted array. Commented Mar 26, 2020 at 12:27

1 Answer 1

1

The problem is that you are doing a string comparison instead of a numeric comparison. If you change line 21 from:

    if Werte(j)>Werte(j+1) then

to:

    if Int(Werte(j))>Int(Werte(j+1)) then

it will sort correctly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.