使用多用户形式

时间:2016-12-09 21:22:46

标签: vba excel-vba ado userform excel

我试图通过在Excel中通过VBA构建用户表单来构建数据库的简单前端。表格是多页的。当我在第一页上工作,并使用UserForm1.Show vbModeless打开用户表单时,我没有遇到任何问题。第二页出现了,什么都没有。对于后台,第一页是输入信息以插入数据库的位置,第二页将是编辑这些字段并更新记录的页面。现在我开始构建第二页,当我尝试使用UserForm1.Show vbModeless启动用户窗体时,收到以下错误。每个页面包含的所有内容都是一堆标签,每个标签都带有相应的文本框或组合框。

Run-time error '3704'

Operation is not allowed when the object is closed.

如何打开它以显示它?

调用以打开用户表单的代码是:

Option Explicit

Sub Show_Form()
UserForm1.Show vbModeless
End Sub

初始化代码为:

Private Sub UserForm_Initialize()
Dim conn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim strSQL As String, NextAM As String

With conn
    .Provider = "SQLOLEDB"
    .ConnectionString = "DATA SOURCE = server;Initial Catalog=database;INTEGRATED SECURITY=sspi;"
    .Open
End With

strSQL = "SELECT MAX(RIGHT(AM_Ref,6)) + 1 FROM AM"

rst.Open strSQL, conn

With ThisWorkbook
    If Len(rst(0)) = 3 Then
        .Sheets("Lists").Range("Next_AM") = "AM_000" & rst(0)
    ElseIf Len(rst(0)) = 4 Then
        .Sheets("Lists").Range("Next_AM") = "AM_00" & rst(0)
    ElseIf Len(rst(0)) = 5 Then
        .Sheets("Lists").Range("Next_AM") = "AM_0" & rst(0)
    End If

    Me.AM_Ref.Text = .Sheets("Lists").Range("Next_AM").Value2
End With

rst.Close
Set rst = Nothing
conn.Close
Set conn = Nothing


With Me
    .StartUpPosition = 0
    .Left = Application.Left + (0.5 * Application.Width) - (0.5 * .Width)
    .Top = Application.Top + (0.5 * Application.Height) - (0.5 * .Height)
End With

End Sub

请注意,initialize sub与之前相同。如果我一直不清楚(可能)请告诉我,我可以澄清一下。

干杯!

1 个答案:

答案 0 :(得分:-1)

快速修复,你应该关闭并运行:

1)将Private Sub UserForm_Initialize()更改为Public Sub UserForm_Initialize()

2)当您想要启动UserForm时,在主子网站中使用以下内容:

Public Sub MasterSub()
   Dim UserForm as UserForm1
   .... code ..... 
   'Now ready to use the UserForm:
   Set UserForm = New UserForm1
   'UserForm will already be initialized and ready to be shown if you did not include that in your initialize sub
   UserForm.Show
End Sub

希望这有帮助, TheSilkCode