协助调试vba模块

时间:2017-06-10 00:34:35

标签: excel vba

我想知道是否有人可以协助我调试以下模块,我相信我唯一的问题在于最后一个(if)语句,以便用一种颜色填充单元格。通用模块创建一个随机数字的单元格范围,如果在输入框中输入了某个值的输入,则应使用红色填充这些数字范围。谢谢!

Option Explicit

Sub test()

Dim i As Integer
Dim j As Integer
Dim user As Integer
Dim cell As Range
Dim random_number As Integer
Dim itm As Integer


For Each cell In Range("A1:J10")

random_number = Int(100 * Rnd) + 1
cell.Value = random_number

Next

Dim mycount As Integer
 
Dim myarray(1 To 10, 1 To 10)

For i = 1 To 10
    For j = 1 To 10
         myarray(i, j) = Cells(i, j).Value
Next
Next

user = CInt(InputBox("enter a number betweeen 1 and 100"))
If user < 1 Or user > 100 Then
    msgbox ("Error, wrong value entered")
    Exit Sub
End If


For i = 1 To 10
    For j = 1 To 10
        If myarray(i, j) > user Then
           Range(Cells(i, j)).Interior.Color = RGB(255, 0, 0)


    itm = itm + 1
        End If

Next
Next


      
msgbox itm

     

End Sub

1 个答案:

答案 0 :(得分:1)

请参阅@ Gary的sStudent评论以调试您的代码。

如果您愿意学习使用数组,范围和Excel / VBA二人组的惊人功能,如果您要长期使用此技术,那么必须,请尝试以这种方式重写代码:

Sub test()
  Dim user As Long
  With Worksheets("Sheet1").Range("A1:J10")
    ' Generate random numbers using formula then fix values
    .Formula = "=RANDBETWEEN(1, 100)"
    .value = .value

    ' Enter a number
    user = Application.InputBox("enter a number betweeen 1 and 100", Type:=1) ' <-- Enter a number
    If user < 1 Or user > 100 Then
      MsgBox ("Error, wrong value entered")
      Exit Sub
    End If

    ' Higlight the value using conditional formatting.
    .FormatConditions.Delete
    .FormatConditions.Add(xlCellValue, xlGreater, user).Interior.Color = RGB(255, 0, 0)

   ' Count of items that match the value
    MsgBox Application.CountIf(.Cells, ">" & user)
 End With
End Sub