简体   繁体   中英

vba stuck in a loop and not moving on to next command

i have written the following code:

Public Sub SortMyData()

'approach: convert line to string and concatenate to that as it's a lot less picky than Excel's formats, then replace cell value with the new string.
'          Excel will then define the string type as either Percentage or Scientific depending on the magnitude.
Dim i As Integer
Dim g As Integer
Dim N_Values As Integer
Dim IntermediateString As String

N_Values = Cells(1048576, 2).End(xlUp).Row 'retrieves the final filled row in column 2 (B)

For i = 6 To N_Values 'iteration loop from 6 (first row of value) to N_Values (last filled row)

    If Cells(i, 2).NumberFormat <> "0.0%" Then
        IntermediateString = Cells(i, 2).Value
        Cells(i, 2).NumberFormat = "0.0%"
        Cells(i, 2).Value = Cells(i, 2).Value / 100
    Else
        MsgBox ("The Range of Cells Has Already Been Formated as Percentage")
    End If
Next i

For g = 6 To N_Values 'iteration loop from 6 (first row of value) to N_Values (last filled row)
    If Len(Cells(g, 3) > 3) Then
        Cells(g, 3).Value = Cells(g, 3).Value / 1000
    Else
        MsgBox ("Data is correct so no action will be taken")
    End If
Next g
End Sub

the code runs fine but it does not move onto the secont if statement, it just keeps on running the first one and displaying the MsgBox ("The Range of Cells Has Already Been Formated as Percentage") so i dont know where i have made a mistake? i am a rookie by the way so go easy on me!

You declare the string :

Dim IntermediateString As String

Then you affect a value to it (by the way, the .Value is optional, cells(x, y) and cells(x, y).Value are the same) :

IntermediateString = Cells(i, 2).Value

But then you don't do anything with this string, so I'm pretty sure that's not what you intended to do (you could comment both of those line, your program would run the same way).

Also, seeing as your program is coded, you should have at most as much messages "The Range of Cells Has Already Been Formated as Percentage" as the number of lines in the B column, but it should eventually keep going to reach second if statement.

I suggest you open the execution window (Ctrl + G), and replace the occurences of "MsgBox" in your code by Debug.Print. You will see the message in the execution window, but it won't pause the execution of the program (much better way to debug)

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