基本VBA - 循环和输入框

时间:2018-02-06 08:02:55

标签: arrays excel vba excel-vba loops

我需要帮助完成一些非常基本的VBA编码。

到目前为止,我已经能够将1到100之间的随机数放入某个范围(A1:J10),并从工作表中读取值并将它们存储在Integer的二维数组中。

但是,我需要帮助:

  1. 循环遍历数组中的值并计算大于用户指定值的值的数量(想到InputBox,同时记住将值从字符串转换为整数,还需要使用if语句来确定数字在1到100之间。结果需要显示在消息框中
  2. 然后,它需要循环遍历范围内的所有值,并使用大于指定数字的值以蓝色对单元格进行着色。
  3. 有人可以帮忙吗?这就是我到目前为止所拥有的

    Sub numrange()
        Dim r As Range
        Set r = Range("A1:J10")
        r.Formula = "=randbetween(1,100)"
    
        Dim arr As Variant
        Dim i As Integer, j As Integer
    
        arr = Range("A1:J10").Value
        ReDim arrint(LBound(arr, 1) To UBound(arr, 1), _
            LBound(arr, 2) To UBound(arr, 2)) As Integer
        For i = LBound(arr, 1) To UBound(arr, 1)
            For j = LBound(arr, 2) To UBound(arr, 2)
                arrint(i, j) = arr(i, j)
            Next
        Next
    End Sub
    

2 个答案:

答案 0 :(得分:0)

假设您已经完成并成功实现了您的想法,请尝试:

编辑1:添加InputBox

Sub marine()

    Dim r As Range, iCnt As Integer
    Dim arr, iVal
    Dim i As Long, j As Long, myprompt As String

    Set r = Sheet1.Range("A1:J10") '/* change Sheet1 to your actual sheet */
    r.Formula = "=RANDBETWEEN(1,100)"
    r.Interior.Color = xlNone '/* remove existing formatting */

    arr = r.Value2
    myprompt = "Please enter numbers between 1 to 100."
    Do
        iVal = InputBox(myprompt, "Count and color")
        myprompt = "You entered an invalid number." & vbNewLine & _
                   "Please enter number between 1 and 100 only."
        If iVal = "" Then Exit Sub '/* if user cancels */
        If Not IsNumeric(iVal) Then
            myprompt = "Invalid entry, numeric value expected." & vbNewLine & _
                       "Please enter numbers between 1 and 100."
        End If
    Loop Until iVal >= 1 And iVal <= 100

    iCnt = 0
    For i = LBound(arr, 1) To UBound(arr, 1)
        For j = LBound(arr, 2) To UBound(arr, 2)
            If arr(i, j) > CInt(iVal) Then
                iCnt = iCnt + 1
                r.Item(i, j).Interior.Color = RGB(0, 0, 255)
            End If
        Next
    Next
    MsgBox "Total of " & iCnt & " number(s) greater than " & iVal

End Sub

答案 1 :(得分:0)

没有数组的更短解决方案:

Sub numrange()
  Dim r As Range, count As Integer, number As Variant
  Set r = Range("A1:J10")

  r.Formula = "=randbetween(1,100)"
  r.Interior.ColorIndex = 0

  count = 0
  number = InputBox("Insert number between 1 and 100")
  If number >= 1 And number <= 100 Then
    For Each cell In r
      If cell > CInt(number) Then
        count = count + 1
        cell.Interior.ColorIndex = 5
      End If
    Next
    MsgBox count & " numbers are greather than " & number
  Else
    MsgBox "Not a valid number"
  End If
End Sub