VBA:在不创建/调用表单的情况下将数据从表单传递到子表单

VBA: Passing data from a form to a sub without creating / calling the form

提问人:CookingCroissants 提问时间:10/30/2023 最后编辑:AdaCookingCroissants 更新时间:11/2/2023 访问量:20

问:

我的代码的目的是从 excel 工作表和用户表单中读取数据,以创建要发送详细信息的电子邮件。它部分基于本教程:https://excelmacromastery.com/vba-userform/

我目前的代码有三个部分:

  • 用户表单代码 在我的模块中:
  • 发送电子邮件
  • 显示形式

DisplayForm 创建用户表单并初始化/显示它。 DisplayForm 是从主子 SendEmails 调用的。 我找不到在 SendEmails 中使用表单变量的方法。

Sub SendEmails()
    
    Dim OutApp As Object
    Dim OutMail As Object
    Dim ws As Worksheet
    Dim iRow As Integer
    Dim FilterItem As String
    Dim FilterColumn As Range
    Dim FilterRange As Range

    Call DisplayForm
      
    Set OutApp = CreateObject("Outlook.Application")
    Set ws = ThisWorkbook.Sheets("Test") 'Change to the name of your sheet
    iRow = 2 'Start from the second row (assuming headers in row 1)
    
    FilterItem = Trade
    Set FilterColumn = ws.Columns("C") ' Change "C" to the column letter that contains the trade info
    Set FilterRange = FilterColumn.Find(What:=FilterItem, LookIn:=xlValues)
    
    MsgBox "Filter Item: " & FilterItem
    MsgBox "Trade: " & Trade
    
    If Not FilterRange Is Nothing Then
        Do Until IsEmpty(ws.Cells(iRow, 1))
           If ws.Cells(iRow, FilterColumn.Column).Value = FilterItem Then

''Rest of code to create email below
Sub DisplayForm()

    ' Create form
    Dim frm As New UserForm1
   '' Set frm = New UserForm1

    ' Display the UserForm
    frm.Show
    
    ' Check if the user cancelled the UserForm
    If frm.Cancelled = True Then
        MsgBox "The UserForm was cancelled."
    Else
        MsgBox "You entered:" & vbCrLf & _
                "Project name: " & frm.ProjectName & vbCrLf & _
                "Doc transfer method: " & frm.DocTransfer & vbCrLf & _
                "Start and finish date: " & frm.Start & " and " & frm.Finish & vbCrLf & _
                "Price Type: " & frm.Prices & vbCrLf & _
                "Trade: " & frm.Trade & vbCrLf & _
                "Quote due date: " & frm.DueDate & vbCrLf & _
                " "
    End If
       
     ' Clean up
    Unload frm
    Set frm = Nothing

End Sub

我试过:

  • 将值分配给 DisplayForm 中的变量,然后将其传递给 SendEmails。
  • 直接使用值(正如我在表单代码的公共属性中定义的那样)
Public Property Get Info() As String

    PName = ProjectName.Value
    Start = Start.Value
    Finish = Finish.Value
    Due = DueDate.Value

    RFQtype = TypeRFQ.Value
    DocTransf = DocTransfer.Value
    Prices = Prices.Value
    Trade = Trade.Value

End Property
  • 我试图查找但找不到答案的是:如果我不能直接使用变量,那么我是否需要调用 Info 函数,在这种情况下,我该怎么做?

谢谢!

编辑:我已在模块级别而不是在DisplayForm子中设置了“Dim frm As Userform1”行。这似乎解决了我的问题,但我想知道这样做有什么问题吗?那么这是否意味着我的“公共财产获取信息”已经过时了?(我想我不完全确定该功能在这里的作用,即使在广泛搜索之后)

VBA7的

评论


答: 暂无答案