如何从函数返回变量字符串并引用子字符串中的字符串

时间:2017-03-28 20:04:13

标签: excel vba function

我目前正在处理VBA表格,该表格将根据相对切换按钮的真/假值通过电子邮件发送某些单元格值。我正在使用相当多的切换按钮,并且正在寻找添加函数以使用相应的切换按钮值返回单元格值的字符串。但是,我当前的字符串返回变量是空白的。

我目前有以下电子邮件子,通过命令按钮调用:

Public Sub Send_Email_Using_VBA()
Dim Email_Subject, Email_Send_From, Email_Send_To, _
Email_Cc, Email_Bcc, Email_Body, First_Name, Second_Name, Third_Name As String
Dim example As Range
Dim callOutString As String
Dim Mail_Object, Mail_Single As Variant

Email_Subject = "Check Sheet Completed"
Email_Send_From = "myemail@email.com"
Email_Send_To = "name@email.com"
Email_Cc = ""
Email_Bcc = ""
Email_Body = ""
On Error GoTo debugs
Set Mail_Object = CreateObject("Outlook.Application")
Set Mail_Single = Mail_Object.CreateItem(0)
With Mail_Single
.Subject = Email_Subject
.To = Email_Send_To
.CC = Email_Cc
.BCC = Email_Bcc
.Body = Email_Body & bodyString 'trying to call/add resulting string from the below sub
.Send
End With
debugs:
If Err.Description <> "" Then MsgBox Err.Description
End Sub

我试图调用/返回&#34; bodyString&#34;的字符串值。来自以下子目录:

'Checks sheet for true toggle boxes which need immediate attention or notice and adds those descriptors to the email body.
Private Sub CommandButton5_Click()

Dim bodyString As String
Dim x As Integer
x = 1

'togglebutton2 check to see if active
If ToggleButton2 = True Then
    If x = 1 Then
        bodyString = "This item: " & Range("A14").Value & " is Bad"
    End If
    x = x + 1
End If

If x = 1 Then
    MsgBox "No items need attention"
    bodyString = "No items need attention"
Else
    MsgBox x - 1 & " Items Need Attention:" & vbCrLf & vbCrLf & bodyString
    bodyString = x - 1 & " Items Need Attention:" & vbCrLf & vbCrLf & bodyString
End If

End Sub

在上面的最终If / Else语句中,我使用MsgBox函数显示bodyString以确保它存储正确的数据。

例如,MsgBox将显示:没有项目需要注意。但是bodyString变量返回一个空格。

1 个答案:

答案 0 :(得分:2)

变量bodyString在事件处理程序`Sub CommandButton5_Click()中定义,并且不能从该子例程返回其值。

要解决此问题,请将bodyString的声明移出Sub CommandButton5_Click()例程,并将其放置在模块级别(在所有函数和子例程之外)声明。然后Sub Send_Email_Using_VBA()将能够访问该变量并保持其内容。