简体   繁体   English

VBA Do 循环直到 0 或 ""

[英]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".它一直在运行代码,直到用户键入“0”。

How can I ensure that the "0 class" won't be counted as an additional class?我怎样才能确保“0 类”不会被算作额外的类? 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 .目前我通过从 B 中减去 -1 来实现它,但这不是一个优雅的解决方案 - 计算是正确的,但该类仍列在最终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.简单Loop Until Zak = ""不起作用。

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.一种常见的方法是先询问,然后使用Do While而不是Loop Until ,然后再次询问。 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.此外,使用您的代码k将是一个变体。

Second, I was able to remove the B - 1 hack while also assuring `B' had a value to avoid a divide by zero error.其次,我能够删除B - 1 hack,同时还确保“B”具有避免除以零错误的值。

Third, this code handles Cancel from the InputBox.第三,此代码处理来自 InputBox 的取消。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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