如何从一个函数返回一个variablesstring,并引用一个子string

我目前正在研究一个VBA工作表,它将根据相对切换button的真/假值通过电子邮件发送某些单元格值。 我正在使用相当多的切换button,并且正在研究添加一个函数来返回单元格值的string与相应的切换button值。 但是,我当前的string的返回variables是空白的。

我目前有下面的电子邮件子,这是通过命令button调用:

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 

我试图从下面的子项调用/返回“bodyString”的string值:

 '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将显示:没有项目需要注意。 然而bodyStringvariables返回一个空白。

variablesbodyString是在事件处理程序Sub CommandButton5_Click()中定义的,它的值不能从这个子例程中返回。

为了解决这个问题,将bodyString的声明移出Sub CommandButton5_Click()例程,并将其放置在模块级声明(所有函数和子例程之外)。 然后Sub Send_Email_Using_VBA()将能够访问该variables,其内容将被保留。