使用使用vba判断一个5位数中有几个相同数字,几个不相同数字
时间: 2024-05-08 20:16:08 浏览: 191
VBA数组合并,去除数组中的相同项
以下是一个VBA示例代码,用于判断一个5位数中有几个相同数字和几个不同数字:
```VBA
Sub CheckDigits()
Dim num As String
Dim i As Integer
Dim j As Integer
Dim same As Integer
Dim diff As Integer
num = InputBox("Please enter a 5-digit number:")
If Len(num) <> 5 Then
MsgBox "Invalid input. Please enter a 5-digit number.", vbExclamation
Exit Sub
End If
For i = 1 To 9
Dim count As Integer
count = 0
For j = 1 To 5
If Mid(num, j, 1) = i Then
count = count + 1
End If
Next j
If count > 1 Then
same = same + 1
ElseIf count = 1 Then
diff = diff + 1
End If
Next i
MsgBox "There are " & same & " same digits and " & diff & " different digits in the number " & num & ".", vbInformation
End Sub
```
在这个示例代码中,我们首先要求用户输入一个5位数,然后使用一个循环来针对每个数字统计出现次数。如果一个数字出现了超过一次,我们就将其看作是“相同数字”,否则就是“不同数字”。最后,我们将结果以消息框的形式显示出来。
阅读全文