Excel VBA Else没有if

问题描述 投票:0回答:3

我想使用if函数来区分两种情况。

For Each Cell In Tabelle3.Range("A" & lastrow2)

Option A: If Cell <> "" Then run code
Option B: If Cell = "" Then skip this empty cell and go on with the next one

这里整个代码:

Sub IfFunction()

Dim lastrow2 As Long
lastrow2 = Tabelle3.Range("A" & Rows.Count).End(xlUp).Row
Set myrange2 = Tabelle8.UsedRange


    For i = 2 To lastrow2

    For Each Cell In Tabelle3.Range("A" & lastrow2)

    If Cell = "" Then i = i + 1

    Else: i = i



        Tabelle3.Cells(7 + i, 19) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 3, False)



        Tabelle3.Cells(7 + i, 20) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 4, False)



        Tabelle3.Cells(7 + i, 21) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 5, False)

        Next i

    End If


End Sub

当我尝试运行此代码时,它不会执行,因为出现错误,即存在'没有IF'功能的ELSE。

有谁知道如何在这里使用IF功能或使用什么?谢谢。 :)

excel vba excel-vba
3个回答
5
投票

如果你继续在Then之后写作,这意味着If语句只包含一行:

If Cell = "" Then i = i + 1 'End If automatically here

那么Else也必须在那条线上:

If Cell = "" Then i = i + 1 Else i = i 'End If automatically here

如果你想使用多行If语句

If Cell = "" Then 
    i = i + 1
Else
    i = i
End If

But …

因为i = i没有做任何你可以写的东西

If Cell = "" Then i = i + 1

并完全省略Else部分,因为它什么都不做。


And anther but …

因为你正在使用For iNext i会自动增加i,你不需要自己增加它。没有i = i + 1需要


0
投票

你的代码只有For但只有一个Next,这会导致语法错误

此外,Next iIf-Then-Else块代码交织在一起,这也会导致语法错误

最后我想你是沿着Tabelle3列迭代两次A从第2行到最后一个不是空的,而你只需要它一次

总结一下,我会说你可以使用这段代码:

Option Explicit

Sub IfFunction()
    Dim myrange2 As Range, cell As Range
    Set myrange2 = Tabelle8.UsedRange

    With Tabelle3
        For Each cell In .Range("A2:A" & .Cells(.Rows.count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants)
            cell.Offset(7, 18) = Application.WorksheetFunction.VLookup(cell.Offset(7), myrange2, 3, False)

            cell.Offset(7, 19) = Application.WorksheetFunction.VLookup(cell.Offset(7), myrange2, 4, False)

            cell.Offset(7, 20) = Application.WorksheetFunction.VLookup(cell.Offset(7), myrange2, 5, False)
        Next
    End With
End Sub

0
投票

好的,这实际上很简单:D我两次运行同一列

For Each Cell In Tabelle3.Range("A" & lastrow2)

If Cell = "" Then i = i + 1

Else: i = i 

For i = 2 To lastrow2

相反,我可以简单地使用:

For i = 2 To lastrow2

If Tabelle3.Cells(7 + i, 1) <> "" Then



Tabelle3.Cells(7 + i, 19) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 3, False)



Tabelle3.Cells(7 + i, 20) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 4, False)



Tabelle3.Cells(7 + i, 21) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 5, False)

End if
Next i

非常感谢您的帮助和贡献!

© www.soinside.com 2019 - 2024. All rights reserved.