我正在尝试创建一个循环遍历范围内的电子邮件地址列表的宏,如果该值不等于#N / A,则会创建标准的模板化电子邮件。由于列表会随着时间的推移而改变,因此我允许用户向单元格“B1”添加行号以使范围计数动态化。
以上工作正常,但由于某种原因,当我尝试运行它时,它一直给我运行时错误'91'消息,这是我的循环中的建议和问题。
代码如下,我已经评论了出现错误的行。
一如既往,感谢帮助。
Sub generateEmail()
Application.ScreenUpdating = False
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Set OutApp = CreateObject("Outlook.Application")
Dim rng As Range
Dim c As Range
Dim endNum As Long
'Set the last row number in range for loop to look through
endNum = ActiveSheet.Range("B1").Value
Set rng = ActiveSheet.Range("B3:B" & endNum)
'Loop through range and if cell value equals #N/A then skip and move on to next one
For Each c In rng.Cells
If cell.Value <> "#N/A" Then '<< ERROR HIGHLIGHTED ON THIS LINE
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = cell.Value
.Subject = "Test Email"
'.Body = " "
.Display
End With
End If
Next c
Application.ScreenUpdating = True
End Sub
写If Not IsError(c) Then
而不是If c.Value <> "#N/A" Then
。
尝试下面的行而不是你的错误行
c.Value<>CVErr(xlErrNA)
我想出了这个问题。我用cell和c做同样的事情。我只需要其中一个变量,然而,它会跳过代码的#N / A过滤器片段。
这是我修改后的代码:
Sub generateEmail()
Application.ScreenUpdating = False
'Set variables
Dim OutApp As Object
Dim OutMail As Object
Dim rng As Range
Dim c As Range
Dim endNum As Long
'Set Outlook App
Set OutApp = CreateObject("Outlook.Application")
'Set the last row number in range for loop to look through
endNum = ActiveSheet.Range("B1").Value
Set rng = ActiveSheet.Range("B3:B" & endNum)
'Loop through range and if cell value equals #N/A then skip and move on to next one
For Each c In rng.Cells
If c.Value <> "#N/A" Then '<< ERROR HIGHLIGHTED ON THIS LINE
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = c.Value
.Subject = "Test Email"
'.Body = " "
.Display
End With
End If
Next c
Application.ScreenUpdating = True
End Sub