在Excel VBA中对范围进行循环或其他工具

时间:2018-09-24 10:44:59

标签: excel vba

我不是程序员,但试图在 VBA Excel中自动执行我的日常工作。

我在VBA中为我的表编写了“ If else”代码一行,并且可以正常工作。但是在我的桌子上有20行。我需要在每一行中处理“ If else”条件。变量必须更改数据,执行条件并转到另一行等。

我想象代码的逻辑,假设我需要 LOOP 作为范围。但是我不明白Loop的语法。

在我的代码下面。

变量:文本,score1,score2,score3-必须更改每行中的单元格。执行后,转到他下面的下一行。

如果“其他”条件必须在(范围)的每一行中起作用。执行后,转到他下面的下一行。

结果-在“过去值”之后,转到他下面的下一行,然后在该行的下一行再输入下一个 If Else 条件的新值。

请帮助我解决此任务。

Sub Test()

Dim score1 As Double, score2 As Double, score3 As Double, result As String, text As String

text = Range("G3").Value
score1 = Range("C3").Value
score2 = Range("D3").Value
score3 = Range("E3").Value

name1 = "Company A"       
name2 = "Company B"
currenc = "Dollars"


If score1 = 0 And score2 = 0 Then
    result = text + " " + name1 + " didn't count and " + name2 + " didn't count."

ElseIf score1 = score2 Then
    result = text + " " + name1 + " some code..............."

ElseIf score1 > score2 And score2 <> 0 Then
    result = text + " " + name1 + "  some code..............."

ElseIf score1 < score2 And score1 <> 0 Then
    result = text + " " + name1 + "  some code..............."

Else
    result = text + " 00000000"

End If

Range("I3").Value = result

End Sub

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

Dim ifrom as long, ito as long
Dim i As Long

ifrom = 3
ito = Range("G3").End(xlDown).Row ' find the row above the 1st blank cell in column G

name1 = "Company A"       
name2 = "Company B"
currenc = "Dollars"

For i = ifrom to ito

    text = Range("G" & i).Value
    score1 = Range("C" & i).Value
    score2 = Range("D" & i).Value
    score3 = Range("E" & i).Value

    If score1 = 0 And score2 = 0 Then
        result = text + " " + name1 + " didn't count and " + name2 + " didn't count."
    ElseIf score1 = score2 Then
        result = text + " " + name1 + " some code..............."
    ElseIf score1 > score2 And score2 <> 0 Then
        result = text + " " + name1 + "  some code..............."
    ElseIf score1 < score2 And score1 <> 0 Then
        result = text + " " + name1 + "  some code..............."
    Else
        result = text + " 00000000"
    End If

    Range("I" & i).Value = result
Next i