此if语句应该查看单元格并根据该单元格中的内容执行操作。如果我只保留语句的第一行,代码就可以运行,它只会执行我希望它为这种情况做的事情。但是,如果我在“Then”之后添加多个“任务”,它只会在整个程序中一直运行。我知道我在这里缺少一些语法会使它“If [this]然后[this,this and this] ElseIf [this]然后[this this and this]。
将第二个第六个“If”变为“ElseIf”会给出错误“ElseIf without block If”
让我知道我缺少什么,我猜测For,Next等的一些迭代但是我不熟悉那个功能。
Sub trythis()
Dim tol As String
Dim formblah As String
tol = Range("I7").Value
formblah = "=IF(D21>C21+" & tol & ",""FAIL"",IF(D21<C21+" & tol & ",""PASS"",IF(D21=C21+" & tol & ",""PASS-BONUS"",""N/A"")))"
If Sheets("Caliper").Range("C5").Value = 1 Then Rows("21:26").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow
Range("E21:E26").Value = formblah
Range("C21") = 1
Range("C21").Select
Selection.DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, _
Step:=1, Stop:=6, Trend:=False
ElseIf Sheets("Caliper").Range("C5").Value = 2 Then Rows("21:28").Insert
Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow
Range("E21:E28").Value = formblah
Range("C21") = 1
Range("C21").Select
Selection.DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, _
Step:=1, Stop:=8, Trend:=False
答案 0 :(得分:4)
对于多行IF,您不能在Then之后立即声明,只能在块内。此外,您需要一个结束如果
像这样:
If Sheets("Caliper").Range("C5").Value = 1 Then
Rows("21:26").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow
Range("E21:E26").Value = formblah
Range("C21") = 1
Range("C21").Select
Selection.DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, _
Step:=1, Stop:=6, Trend:=False
ElseIf Sheets("Caliper").Range("C5").Value = 2 Then
Rows("21:28").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow
Range("E21:E28").Value = formblah
Range("C21") = 1
Range("C21").Select
Selection.DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, _
Step:=1, Stop:=8, Trend:=False
End If
另外,请见她:https://www.techonthenet.com/excel/formulas/if_then.php
答案 1 :(得分:0)
as already answered, you have to keep all statements inside the If-Else
and Else-End If
blocks
but you could:
adopt a Select Case
block, to handle more cases and achieve more readability
keep the real code outside the If-Then-Else-End If
(or Select Case-End Select
) block where to just set relevant changing variables
as follows:
Sub trythis()
Dim tol As String
Dim formblah As String
tol = Range("I7").Value
formblah = "=IF(D21>C21" & tol & ",""FAIL"",IF(D21<C21" & tol & ",""PASS"",IF(D21=C21" & tol & ",""PASS-BONUS"",""N/A"")))"
Dim nRows As Long
Select Case Sheets("Caliper").Range("C5").Value
Case 1
nRows = 6
Case 2
nRows = 8
Case 3
' if needed, add you case handling
Case Else
' if needed, add you case handling
End Select
Rows("21").Resize(nRows).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow
Range("E21").Resize(nRows).Formula = formblah
Range("C21").Value = 1
Range("C21").DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, Step:=1, Stop:=6, Trend:=False
End Sub