excel if else循环不带条件地执行else部分[closed]

mi7gmzs6  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(158)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
4天前关闭。
Improve this question

(No title)
If Rcount >= 2 Then
    For Rnum = 2 To Rcount
        'Filter the FilterRange on the FieldNum column
        FilterRange.AutoFilter Field:=FieldNum, _
                                   Criteria1:=Cws.Cells(Rnum, 1).Value
        'Look for the mail address in the MailInfo worksheet
        mailAddress = ""
        On Error Resume Next
        mailAddress = ""
        On Error Resume Next
        mailAddress = Application.WorksheetFunction. _
            VLookup(Cws.Cells(Rnum, 1).Value, _
            Worksheets("Mailinfo").Range("A1:C" & _
            Worksheets("Mailinfo").Rows.Count), 3, False
 
        If mailAddress = "" Then               
            Ash.Cells(Rnum, 23) = "Email Missing for " & Ash.Cells(Rnum, 7)
        ElseIf mailAddress <> "" Then
            With Ash.AutoFilter.Range
                On Error Resume Next
                Set rng = .SpecialCells(xlCellTypeVisible)
                On Error GoTo 0
            End With
            Set OutMail = OutApp.CreateItem(0)
            'On Error Resume Next
            With OutMail
                .To = mailAddress
                .CC = Str6
                .Subject = Str5
                .HTMLBody = Str1 & Str2 & RangetoHTML(rng) & Str3 & Str4
                .Display  'Or use Display
            End With
            On Error GoTo 0
            Ash.Cells(Rnum, 23) = "Email Sent"
            Set OutMail = Nothing
        Else
            'Nothing
        End If
        'Close AutoFilter
        Ash.AutoFilterMode = False
    Next Rnum
End If

这是罗恩de bruin代码的一个片段。稍微改动了一下。即使工作表中存在邮件地址,代码也会执行else部分。
此外,如果有多个单元格具有相同的名称。它不会将已发送的电子邮件粘贴到每个单元格上。

3z6pesqy

3z6pesqy1#

这并不是一个完整的答案或解决方案,因为我认为我们没有足够的信息来真正找出你的问题。但我强烈建议创建单独的行和中间变量。例如,你的语句:

mailAddress = Application.WorksheetFunction. _
        VLookup(Cws.Cells(Rnum, 1).Value, _
        Worksheets("Mailinfo").Range("A1:C" & _
        Worksheets("Mailinfo").Rows.Count), 3, False

可以失败在许多方面,这是很难找出原因。
它在内存和执行速度方面完全没有成本,如果你创建中间变量,它会极大地增强你程序的可读性(和调试能力)。例如:

Dim findThis As String
findThis = Cws.Cells(Rnum, 1).value

Dim mailInfo As Worksheet
Set mailInfo = Thisworkbook.Worksheets("Mailinfo")
With mailInfo
    Dim lastRow As Long
    lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    
    Dim inThisRange As Range
    Set inThisRange = mailInfo.Range("A1:C" & lastRow)
End With

Dim mailAddress As String
mailAddress = Application.WorksheetFunction. _
                  VLookup(findThis, inThisRange, 3, False)

虽然我在这里进行了猜测,但现在可以检查findThislastRowinThisRange.Address的值,以验证代码是否确实在正确的范围内。
对代码的其他大部分部分部分也这样做(养成习惯!),这应该会有所帮助。

相关问题