Sudrabs
Sudrabs

Reputation: 1

Code won't acknowledge the odd numbers, not placing them in column B

The task is to write a code that will import the text from a .txt file. In this task, I am to sort the pair and odd numbers in different columns A,B. The code runs fine by copying over the work of the pair numbers (from the .txt file) but doesn't even copy over the odd numbers.

Tried changing the formula, this is the only one that works.

Close #1
Dim xopen As Variant
Dim xclose As Variant

xopen = Application.GetOpenFilename

If xopen = "False" Then
    MsgBox "error nav fails"
Else
    Open xopen For Input As #1
    i = 1
    j = 1
    Do Until EOF(1)
        Line Input #1, st

        If IsNumeric(st) = False Then
            MsgBox "error nav skaitlis(number)"
            Close #1
            Close #2
            Exit Do
        End If

        Line Input #1, st
        If st > 0 Then
            Cells(i, 1) = st
            i = i + 1
        Else
            If Val(st) Mod 2 = 1 Then
                Cells(j, 2).Value = st
                j = j + 1
            End If
        End If
    Loop

    Close #1
    xclose = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt),*.txt")
    ThisWorkbook.SaveAs Filename:=xclose, FileFormat:=xlText
End If

Upvotes: 0

Views: 55

Answers (2)

Sudrabs
Sudrabs

Reputation: 1

''' Line Input #1, st

    If IsNumeric(st) = False Then
        MsgBox "error nav skaitlis(number)"
        Close #1
        Close #2
        Exit Do
    End If

''' This was the cause of the problem, deleting this would solve it and let me copy over the odd numbers. It kept looping through that phase. And wouldn't let it go past it.

Upvotes: 0

riskypenguin
riskypenguin

Reputation: 2199

Your problem is inside the If - Else logic, try this code and see below for an explanation:

If st > 0 Then
    If st Mod 2 = 0 Then
        Cells(i, 1).Value2 = st
        i = i + 1
    Else
        Cells(j, 2).Value2 = st
        j = j + 1
    End If
End If

The way your code is written you can only enter the Else statement when your number st is <= 0. But you actually want to check if the number is larger than 0 and if that is true split the numbers into odd and even numbers. Basically your Else was in the wrong place.

Upvotes: 1

Related Questions