处理仅在硬编码范围内具有值的单元格

时间:2018-02-14 20:12:03

标签: excel vba excel-vba

我有代码可以在“G”列中为所有收件人起草电子邮件。

    Sub Send_Bulk_Mail()

    Dim objOutlook As Object
    Dim objMail As Object
    Dim ws As Worksheet

    Set objOutlook = CreateObject("Outlook.Application")
    Set ws = ActiveSheet

  For Each cell In ws.Range("G2:G100")

    Set objMail = objOutlook.CreateItem(0)

        With objMail
            .To = cell.Value
            .Subject = "This is the test subject"
            .Body = "This is the test email body"
            .Send
        End With

        Set objMail = Nothing
    Next cell

    Set ws = Nothing
    Set objOutlook = Nothing

End Sub

如果G列中的行数少于100,则在草拟所有电子邮件后会出错。

如何在上一封电子邮件后自动停止?

以下是示例Click here

的链接

2 个答案:

答案 0 :(得分:3)

或只使用Range.End Property (Excel)

Dim rCell As Range
For Each rCell In Ws.Range("G2", Ws.Range("G100").End(xlUp))
     'code here 
Next rCell

完整示例

Option Explicit
Sub Send_Bulk_Mail()
    Dim objOutlook As Object
    Dim objMail As Object
    Dim Ws As Worksheet

    Set objOutlook = CreateObject("Outlook.Application")
    Set Ws = ActiveSheet

    Dim rCell As Range
    For Each rCell In Ws.Range("G2", Ws.Range("G100").End(xlUp))
        Debug.Print rCell.Address
        Set objMail = objOutlook.CreateItem(0)

        With objMail
            .To = rCell.Value
            .Subject = "This is the test subject"
            .Body = "This is the test email body"
            .Send
        End With

    Next rCell

    Set objMail = Nothing
    Set Ws = Nothing
    Set objOutlook = Nothing

End Sub

在此处查看更多示例https://stackoverflow.com/a/48497589/4539709

答案 1 :(得分:1)

检查tbl以确定在尝试使用它之前是否一无所知。

library(dbplyr)
library(dplyr)
library(pool)
library(DBI)

pool <- dbPool(odbc::odbc(),
               driver = "FreeTDS", 
               server = "server", 
               database = "database", 
               uid = "uid", 
               pwd = "password", 
               port = 1433)
data <- tbl(pool, in_schema("schema.dbo", "table"))

Error: <SQL> 'SELECT *
    FROM schema.dbo.table AS "zzz1"
    WHERE (0 = 1)'
     nanodbc/nanodbc.cpp:1587: 42000: [FreeTDS][SQL Server]Incorrect syntax near 'zzz1'.