我是VBA的新手,并在以下代码中遇到类型不匹配错误。
我收到整数j
的错误。我已将其更改为所有其他数据类型,但仍然相同。
Private Sub CommandButton3_Click()
Dim rng1 As Range, rng2 As Range, i As Integer, j As Integer, k As Integer
Set rng1 = Range("A:A")
Set rng2 = Range("B:B")
j = Application.WorksheetFunction.Lookup(2, 1 / (rng1 <> ""), rng1)
k = Application.WorksheetFunction.Match(j, rng1, 0)
i = 0
For i = i + 1 To k
If Cells(i, 1) Mod 2 = 0 Then
Cells(i, 2) = "Even"
Else: Cells(i, 2) = "Odd"
End If
Next i
MsgBox "There are " & Application.WorksheetFunction.CountIf(rng2, "Even") _
& " Even and " & Application.WorksheetFunction.CountIf(rng2, "Odd") & " Odd numbers"
End Sub
答案 0 :(得分:0)
我的评论:
如果我正确地读取您的代码,您试图找到第一行包含A列最后一个占用行上的值。这是正确的吗?然后你试图弄清楚到目前为止有多少偶数出现以及有多少奇数 - 但是你想从计数中排除除A列中最后一个值的第一次出现以外的任何数字。这是正确的吗? ...
您的回复:
前两个问题完全正确。
示例数据:
如果你真的想找到包含A列最后一个占用行的值的第一行,即上面示例数据中包含3
的第一行,并确定赔率数/平均到那一点并从计数中排除超出该点的任何东西,然后你可以使用以下代码:
Private Sub CommandButton3_Click()
Dim lastUsedRow As Long
Dim lastRow As Long
Dim i As Long
Dim Odds As Long: Odds = 0
Dim Evens As Long: Evens = 0
With ActiveSheet
'Find the last used row in column A (row 9 in example data)
lastUsedRow = .Cells(.Rows.Count, "A").End(xlUp).Row
'Find first row containing the data from the last used row
'(i.e. the first row containing a 3 in the example data, i.e. row 4)
lastRow = Application.Match(.Cells(lastUsedRow, "A").Value, .Range("A:A"), 0)
'Loop from first row to last row
For i = 1 To lastRow
'Decide whether the nearest integer to the value in the cell
'is odd or even
If .Cells(i, "A").Value Mod 2 = 0 Then
.Cells(i, "B").Value = "Even"
Evens = Evens + 1
Else
.Cells(i, "B").Value = "Odd"
Odds = Odds + 1
End If
Next i
MsgBox "There are " & Evens & " Even and " & Odds & " Odd numbers"
End With
End Sub
但是,如果您想对所有行进行计算,则可以使用以下代码:
Private Sub CommandButton3_Click()
Dim lastUsedRow As Long
Dim i As Long
Dim Odds As Long: Odds = 0
Dim Evens As Long: Evens = 0
With ActiveSheet
'Find the last used row in column A (row 9 in example data)
lastUsedRow = .Cells(.Rows.Count, "A").End(xlUp).Row
'Loop from first row to last used row
For i = 1 To lastUsedRow
'Decide whether the nearest integer to the value in the cell
'is odd or even
If .Cells(i, "A").Value Mod 2 = 0 Then
.Cells(i, "B").Value = "Even"
Evens = Evens + 1
Else
.Cells(i, "B").Value = "Odd"
Odds = Odds + 1
End If
Next i
MsgBox "There are " & Evens & " Even and " & Odds & " Odd numbers"
End With
End Sub