首页 文章

使用VBA打开并运行用户表单

提问于
浏览
1

我在一个名为“userform”的excel文件上有一个userform:

Private Sub add1_Change()

End Sub

Private Sub add2_Change()


End Sub

Private Sub Calc_Click()


Result.Value = Val(add1.Value) + Val(add2.Value)



End Sub

此userform从用户获取值并将它们一起添加并在文本框中显示结果 .

我想在另一个名为“input”的工作簿中创建一个新的宏 . 此工作簿中的宏应打开userform工作簿,在文本框add1和add2中输入值,然后运行userform计算按钮 .

到目前为止我尝试过的:

  • 设置 add1.value 以从,例如,单元格A1中提取值,对于 add2.value 也是如此 . 然后我在输入工作簿上创建了一个宏来更改单元格A1和A2中的值 . 这里的问题是我不知道如何强制excel打开用户窗体并单击计算 .

理想情况下,我真的不想完成我所做的事情 . 我想设置一个宏来打开用户窗体,输入数据并点击计算然后关闭用户窗体 - 而不是编辑用户窗体本身

关于如何解决这个问题的任何想法都会非常感激 .

2 回答

  • 0

    你可以用这种方式在 UserForm 中添加2个值(它与你现在尝试的稍微不同):

    您使用当前代码打开 UserForm

    Sub userform()
        Workbooks.Open (ThisWorkbook.Path & "\userform.xlsm")
        Application.Run "userform.xlsm!Calc"
    End Sub
    

    如上所示,您不会在 userform.xlsm Workbook 中分配任何值 .

    下面是你在 UserForm 的sub Initialize 中输入的代码:

    Private Sub UserForm_Initialize()
    
        Dim wb As Workbook
        Dim ws As Worksheet
    
        Set wb = Workbooks("input.xlsx")
        Set ws = wb.Worksheets("Input")
    
        Dim i as Integer
        Dim k as Integer
    
        UserForm.add1.Value = ws.Range("A2").Value
        UserForm.add2.Value = ws.Range("B2").value
        UserForm.calc.Value = val(UserForm.add1.Value) + val(UserForm.add2.Value)
    
    End Sub
    

    如上所示 calc 更改为 Textbox ,因此您无需单击加载UserForm时直接执行的按钮 .

    您也可以使用 Label 而不是 Textbox .

    然后代码将更改为:

    UserForm.calc.Caption = Str( val(UserForm.add1.Value) + val(UserForm.add2.Value) )
    
  • 0

    @DirkReichel你能详细说明一下吗?我已经添加了你说的内容,但是我想改变add1文本框中的值我将如何调用它?现在,我有这个:'Sub userform()Dim a As Integer Dim b As Integer a = Cells(1,2)b = Cells(2,2)Workbooks.Open(ThisWorkbook.Path&“\ userform.xlsm” )Application.Run“userform.xlsm!Calc”End Sub'calc宏只是打开userform,我不知道如何实际“输入”数据或命中计算

    答案:

    我创建了2 WB,这个简单的代码对我有用......但是:您可能需要更改信任中心的设置 .

    Book1模块:( WB与 Userform1 持有 TextBox1CommandButton1

    Option Explicit
    
    Public Function getUF()
      Set getUF = UserForm1
    End Function
    

    Book2模块:

    Option Explicit
    
    Public ExtUF As Variant
    
    Sub the_UF()
      Workbooks.Open "Book1.xlsm"
      Set ExtUF = Application.Run("Book1.xlsm!getUF") 'get the Form
    
      Debug.Print ExtUF.TextBox1.Value  'check old value
      ExtUF.TextBox1.Value = "dada"     'change it
      Debug.Print ExtUF.TextBox1.Value  'check for new value
    
      ExtUF.CommandButton1.Value = True 'hit the button
      ExtUF.Show                        'show the form
       Stop 'to check the userform
      ExtUF.Hide                        'hide it again
    End Sub
    

    现在运行 the_UF 并检查功能 . 如果一切正常,请按照您需要的方式将其应用到您的代码中 .

    如果你有问题,就问吧 ;)

相关问题