VBA范围和字符串混淆

时间:2016-04-19 19:27:08

标签: string excel vba range

想想我对范围和字符串之间的区别有疑问。试图让它搜索任何获胜者范围内的单元格,然后吐出一个点值。

Sub it()
Dim Round1 As Range
Dim Round2 As Range
Dim lngCnt As Long
Dim Winner() As String
Dim pointSum As Double
ReDim Winner(1 To 4)
    Winner(1) = "Mohler"
    Winner(2) = "Scotter"
    Winner(3) = "DKGAY"
    Winner(4) = "Lassie"
Set Round1 = Range("L3,L11,L22,L32").Text
For Each Winner In Round1
lngCnt = lngCnt + 10
Winner(lngCnt) = pointSum.Value
Next
MsgBox pointSum.Value    
End Sub

2 个答案:

答案 0 :(得分:2)

您需要两个循环:

Sub it()
Dim Round1 As Range
Dim Round2 As Range
Dim lngCnt As Long
Dim Winner() As String
Dim pointSum As Double
Dim rng As Range
Dim i As Long
ReDim Winner(1 To 4)
    Winner(1) = "Mohler"
    Winner(2) = "Scotter"
    Winner(3) = "DKGAY"
    Winner(4) = "Lassie"
Set Round1 = Range("L3,L11,L22,L32")
For Each rng In Round1
    For i = 1 To UBound(Winner)
        If rng.Value = Winner(i) Then
            pointSum = pointSum + 10
            Exit For
        End If
    Next i
Next rng

MsgBox pointSum.Value
End Sub

第一个循环遍历范围,第二个循环通过字符串数组。当它找到相等的位置时,它会增加10。

答案 1 :(得分:1)

仅带一个循环的解决方案 我不是在我的电脑上,所以不能用代码标签进行测试或格式化

Sub Main
 Dim Round1 As Range, rng As Range
 Dim Winners As Variant
 Dim pointSum As Double

 Winners =Array ("Mohler","Scotter","DKGAY", "Lassie")
 Set Round1 = Range("L3,L11,L22,L32")
 WinnersStr = "-" & Join (Winners, "-") & "-"
 For Each rng In Round1
     If Instr(WinnersStr, "-" & rng.Value & "-") > 0 Then pointSum = pointSum + 10
Next rng

End Sub