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

问题描述 投票:1回答:2
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”给出了运行时错误,而代码根据条件给出了正确的输出和正确的值。请提出必要的修改建议。

excel vba excel-vba
2个回答
4
投票

你的代码是“尖叫”使用Select Case而不是你的多个Ors。

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

2
投票

不是答案,但你可以简化你的代码,没有Case ;-)

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

(如果你有UCase,则不需要Option Compare Text

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