如何为strBody变量选择单元格范围而不是仅选择2个单元格?

时间:2019-10-08 20:06:55

标签: excel vba

VBA监视窗口在运行此脚本时显示“ strBody”变量和值的“类型不匹配”和“空”。我已经确认此脚本的电子邮件部分有效。我根本无法选择所需的单元格范围。帮助吗?

我希望能够为strBody变量选择一个范围。

如果我将strBody变量替换为以下内容,则一切正常:

strBody = Str(Sheet1.Cells(1, 1)) & Str(Sheet1.Cells(1, 2))

Sub send_email()
Dim NewMail As Object
Dim MailConfig As Object
Dim SMTP_Config As Variant
Dim strSubject As String
Dim strFrom As String
Dim strTo As String
Dim strCc As String
Dim strBcc As String
Dim strBody As Variant

strSubject = "Mail from Excel"
strFrom = "email@gmail.com"
strTo = "email@gmail.com"
strCc = ""
strBcc = ""
strBody = Str(ActiveWorkbook.Sheets("Sheet1").Range("A1:B2"))

1 个答案:

答案 0 :(得分:0)

在不查看数据的情况下,您可以考虑构建UDF:

...
strBody = build_body(ActiveWorkbook.Sheets("Sheet1").Range("A1:B2"))
End Sub

Function build_body(rng As Range, Optional delimiter As String = " ") As String
Dim cel As Range
Dim tmpStr As String
For Each cel In rng.Cells
    If tmpStr <> "" Then tmpStr = tmpStr & delimiter & cel.Value
    If tmpStr = "" Then tmpStr = cel.Value
Next cel
Debug.Print tmpStr
build_body = tmpStr
End Function

带有示例数据:

enter image description here

输出:A1, B1, A2, B2

仅执行Str(Sheet1.Cells(1, 1)) & Str(Sheet1.Cells(1, 2))就会输出A1B1