如果在其他情况下的Vba问题

时间:2017-12-19 07:24:49

标签: excel vba excel-vba

Set ws1 = wb.Worksheets("MacroGeneratedReport")
LastRow = ws1.Cells(Rows.Count, "A").End(xlUp).Row
For i = LastRow To 1 Step -1
If ws1.Cells(i, "I").Value = "A" Or ws1.Cells(i, "I").Value = "B" Or 
 ws1.Cells(i, "I").Value = "C" Or ws1.Cells(i, "I").Value = "D" Or 
 ws1.Cells(i, "I").Value = "E" Or ws1.Cells(i, "I").Value = "F" Or 
 ws1.Cells(i, "I").Value = "Y" Then
 ws1.Cells(i, "AO").Value = ws1.Cells(i, "Y").Value
Else
 **ws1.Cells(i, "AO").Value = ws1.Cells(i, "AP").Value * ws1.Cells(i, "W").Value**
End If
Next i

在上面的代码中,粗体突出显示“Else condition”给出了运行时错误,而代码根据条件给出了正确的输出和正确的值。请提出必要的修改建议。

2 个答案:

答案 0 :(得分:4)

你的代码是"尖叫"使用Select Case代替您的多个Or

<强> 代码

Set ws1 = wb.Worksheets("MacroGeneratedReport")
With ws1
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    For i = LastRow To 1 Step -1
        Select Case .Cells(i, "I").Value
            Case "A", "B", "C", "D", "E", "F", "Y"
                .Cells(i, "AO").Value = .Cells(i, "Y").Value

            Case Else
                ' check that both values are numeric
                If IsNumeric(.Cells(i, "AP").Value) And IsNumeric(.Cells(i, "W").Value) Then
                    .Cells(i, "AO").Value = .Cells(i, "AP").Value * .Cells(i, "W").Value
                End If            
        End Select
    Next i
End With

答案 1 :(得分:2)

不是答案,但您可以简化代码,而不需要Case; - )

If UCase(ws1.Cells(i, "I").Value) Like "[A-FY]" Then

(如果您有UCase

,则不需要Option Compare Text