在for循环中添加条件

时间:2013-07-07 10:13:42

标签: vba loops

我在VBA中有以下两个功能。我的excel看起来像这样。

OddsId  Agt      Ma   Sma     Result
1       Agt1    Ma1   Sma1     x

我的意图是计算x的值。我想添加一个条件,用户可以在Agt,ma和Sma中一次只提供一个值。如果这两个字段中的任何一个非零,那么我的结果应为“Error”。我不确定在这些函数中添加这个条件的位置。

我也不太确定If NOT函数会实际返回什么!! 请帮助我。

Function fcComm1(oddsId As Integer, agt As String, ma As String, sma As String, fcOption1 As Integer)
If Not setFcType(agt, ma, sma) Then
    fcComm1 = "Invalid2"
    Return
End If
For i = 1 To bets.ListRows.Count
    currOddsId = bets.ListColumns("OddsId").DataBodyRange(i)
    currTransId = bets.ListColumns("TransId").DataBodyRange(i)
    currPlayer = bets.ListColumns("Account").DataBodyRange(i)

    If (currOddsId = oddsId) Then
        If FcType = "agt" Then
            currAgt = Application.WorksheetFunction.VLookup(currPlayer, accounts.DataBodyRange, 9, False)
            If (agt <> currAgt) Then
                fcComm1 = ""
                GoTo NextIteration
            End If
        ElseIf FcType = "ma" Then
            currMa = Application.WorksheetFunction.VLookup(currPlayer, accounts.DataBodyRange, 10, False)
            If (ma <> currMa) Then
            fcComm1 = ""
                GoTo NextIteration
            End If
        ElseIf FcType = "sma" Then
            currSma = Application.WorksheetFunction.VLookup(currPlayer, accounts.DataBodyRange, 11, False)
            If (sma <> currSma) Then
            fcComm1 = ""
                GoTo NextIteration
            End If
        End If


        exchangeRate = Application.WorksheetFunction.VLookup(currPlayer, accounts.DataBodyRange, 4, False)
        blindRisk = Application.WorksheetFunction.VLookup(currPlayer, accounts.DataBodyRange, 6, False) / 100#
        fcComm1 = fcComm1 + ForecastBet(currTransId, exchangeRate, blindRisk)

NextIteration:

    End If
Next
End Function



Function setFcType(agt As String, ma As String, sma As String)
setFcType = True

If Len(agt) + Len(ma) + Len(sma) = 0 Then
    FcType = "company"
ElseIf agt <> "" And agt <> "0" Then
    FcType = "agt"
ElseIf ma <> "" And ma <> "0" Then
    FcType = "ma"
ElseIf sma <> "" And sma <> "0" Then
    FcType = "sma"
End If

End Function

1 个答案:

答案 0 :(得分:0)

如果有多个变量不同于&#34;&#34;

,您的setFcType函数的更正版本会返回false。
Function setFcType(agt As String, ma As String, sma As String)
setFcType = True

If ((Len(Trim(agt)) > 0 And (Len(Trim(ma)) > 0 Or Len(Trim(sma)) > 0)) Or (Len(Trim(ma)) > 0 And (Len(Trim(agt)) > 0 Or Len(Trim(sma)) > 0))) Then
    setFcType = False
    Exit Function
End If

If Len(agt) + Len(ma) + Len(sma) = 0 Then
    FcType = "company"
ElseIf agt <> "" And agt <> "0" Then
    FcType = "agt"
ElseIf ma <> "" And ma <> "0" Then
    FcType = "ma"
ElseIf sma <> "" And sma <> "0" Then
    FcType = "sma"
End If

End Function