【问题标题】:Loop or another instrument for range in Excel VBAExcel VBA中的循环或其他仪器范围
【发布时间】:2018-09-24 10:44:58
【问题描述】:

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

我在 VBA 中为我的表格一行写了“If else”代码,它可以工作。但在我的表中有 20 行。而且我需要在每一行工作“如果其他”条件。变量必须更改数据,执行条件并转到另一行等。

我想象代码的逻辑,假设我需要 LOOP 来表示范围。但我不明白循环的语法。

在我的代码下面。

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

If Else 条件必须在每一行(范围内)都有效。执行后转到他下面的下一行。

结果 - 在“过去的值”之后转到他下面的下一行,然后再过去新行的下一个 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

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    试试这个方法:

    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
    

    【讨论】:

    • 太棒了!有用。谢谢你。加个cmets就完美了,想懂逻辑。
    猜你喜欢
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多