简体   繁体   中英

VBA Do loop until 0 or ""

Below code is counting a final amount of students in a school and average amount of students in a class.

It's running the code until the user types "0".

How can I ensure that the "0 class" won't be counted as an additional class? Currently I am achieving it by subtracting -1 from B, but it's not an elegant solution - calculation is correct, but the class is still listed in final MsgBox .

Btw, if I wanted to end the loop when user is leaving the cell empty, what should I do? Simple Loop Until Zak = "" doesn't work.

Many thanks,

Sub D1()

    Dim Zak As Byte
    Dim B As Byte, C As Byte
    Dim kzak As String
    Dim ktrid
    Dim trid As Byte
    Dim k, l As Integer

    B = 0
    kzak = ""

    Do
        Zak = InputBox("Amount of students")
        B = B + 1
        kzak = kzak & Str(B) & (" class") & ("            ") & _
            ("Students ") & Str(Zak) & Chr(10)
        k = k + Zak
    Loop Until Zak = 0
    C = (B - 1)
    l = k / C

    MsgBox kzak & Chr(10) & ("At school is ") & Str(k) & (" students") & _
        (", on avarage ") & Str(l) & (" in a class")

End Sub

A common approach to this is to ask first, and then test with a Do While instead of a Loop Until , and then ask again. Something like this:

Zak = InputBox("Amount of students")
Do While Zak <> 0
    ...
    ...
    Zak = InputBox("Amount of students")
Loop

This is a late post, but here is code to accomplish all the requirements you stated with just a few tweaks to your existing code:

Public Sub D2()
   Dim Zak As String
   Dim B As Integer
   Dim kzak As String
   Dim k As Integer
   Dim l As Integer

   B = 0
   kzak = ""

   Do
      Zak = InputBox("Amount of students")

      If Val(Zak) > 0 Then
         B = B + 1
         kzak = kzak & Str(B) & (" class") & ("            ") & ("Students ") & Zak & Chr(10)
         k = k + Val(Zak)
      End If
   Loop Until Zak = ""

   If B > 0 Then
      l = k / B
      MsgBox kzak & Chr(10) & ("At school is ") & Str(k) & (" students") & (", on avarage ") & Str(l) & (" in a class")
   End If
End Sub

Notice some of the changes I made.

First, I declared the variables more appropriately. Also, with your code k would have been a variant.

Second, I was able to remove the B - 1 hack while also assuring `B' had a value to avoid a divide by zero error.

Third, this code handles Cancel from the InputBox.

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