如何使用循环填写Userform上的多个控件?

时间:2018-03-19 20:05:01

标签: excel vba forms loops

我有以下代码在数据表中查找ID并从其他列返回相应的值。下面是返回单个列值并将其发布到我的表单上的TextBox / ComboBox的代码。但是,我希望将其创建为一个循环,以便发布到我拥有的所有20-30个字段,而不是重复每个字段的代码。

id_1 = OrderDisplay.id

col_no = 3
sales_order = WorksheetFunction.VLookup(id_1, Worksheets("Data").Range("A:AB"), col_no, False)
OrderDisplay.sales_order = sales_order

请注意,我的TextBox / ComboBox有不同的名称,例如客户,网站等。

{{1}}

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

考虑将工作表数据作为数据库进行查询,因为它似乎是表格式结构,您将其作为参数传入特定的 id 。实际上,这可能会使您将工作表升级为实际数据库,如MS Access(Excel&#s; sibling),SQLite等,您可以在其中交换ADO连接字符串,然后在SQL中为数据库表换页!

下面假设您的所有userform控件都与表字段(工作表的第一列)具有相同的确切名称。

Dim conn As Object, rst As Object,  cmd As Object
Dim strSQL As String, id1 As Long

Set conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")

strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
                   & "Data Source='C:\Path\To\Workbook.xlsm';" _
                   & "Extended Properties=""Excel 12.0;HDR=YES;"";"

' OPEN CONNECTION
conn.Open strConnection

' WORKBOOK QUERY
strSQL = "SELECT t.* " _
          & " FROM [SheetName$] AS t" _
          & " WHERE t.id = ?"

id_1 = OrderDisplay.id

' BUILD PARAMETERED QUERY
Set cmd = CreateObject("ADODB.Command")
With cmd
    .ActiveConnection = conn
    .CommandText = strSQL
    .CommandType = adCmdText
    .Parameters.Append .CreateParameter("idparam", adInteger, adParamInput, , id1)
End With

' CREATE RECORDSET
Set rst = cmd.Execute

' LOOP THROUGH RECORDSET AND FILL IN CONTROL VALUES
rst.MoveFirst
Do While Not rst.EOF
    For i = 1 To rst.Fields.Count - 1
        Me.Controls(rst.Fields(i).Name).Value = rst.Fields(i)
    Next i
    rst.MoveNext
Loop

rst.Close: conn.Close    
Set conn = Nothing: Set rst = Nothing: Set cmd = Nothing