将预定义的值放在USERFORM VB查询中

我是新来的macros,但有一些基本的想法是如何工作,或像写能够写VBA的小代码。

我已经创build了一个示例用户窗体,但我想知道如何我可以把值放在代码本身,以便我不想维护一个单独的查找表,以保持所有这些值我的下拉选项可用下创build我的USERFORM。

请find我使用的代码。

Private Sub cmdAdd_Click() Dim lRow As Long Dim lPart As Long Dim ws As Worksheet Set ws = Worksheets("PartsData") 'find first empty row in database lRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _ SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1 lPart = Me.cboPart.ListIndex 'check for a part number If Trim(Me.cboPart.Value) = "" Then Me.cboPart.SetFocus MsgBox "Please enter a part number" Exit Sub End If 'copy the data to the database 'use protect and unprotect lines, ' with your password ' if worksheet is protected With ws ' .Unprotect Password:="password" .Cells(lRow, 1).Value = Me.cboPart.Value .Cells(lRow, 2).Value = Me.cboPart.List(lPart, 1) .Cells(lRow, 3).Value = Me.cboLocation.Value .Cells(lRow, 4).Value = Me.txtDate.Value .Cells(lRow, 5).Value = Me.txtQty.Value ' .Protect Password:="password" End With 'clear the data Me.cboPart.Value = "" Me.cboLocation.Value = "" Me.txtDate.Value = Format(Date, "Medium Date") Me.txtQty.Value = 1 Me.cboPart.SetFocus End Sub Private Sub cmdClose_Click() Unload Me End Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) If CloseMode = vbFormControlMenu Then Cancel = True MsgBox "Please use the Close Form button!" End If End Sub Private Sub UserForm_Initialize() Dim cPart As Range Dim cLoc As Range Dim ws As Worksheet Set ws = Worksheets("LookupLists") For Each cPart In ws.Range("PartIDList") With Me.cboPart .AddItem cPart.Value .List(.ListCount - 1, 1) = cPart.Offset(0, 1).Value End With Next cPart **For Each cLoc In ws.Range("LocationList") With Me.cboLocation .AddItem cLoc.Value End With Next cLoc** Me.txtDate.Value = Format(Date, "Medium Date") Me.txtQty.Value = 1 Me.cboPart.SetFocus End Sub 

我学习如何从一个网站设置这个用户,你可以使用这个链接下载示例excel文件(在该网站上发布)

请帮助我。

提前致谢

比方说,你想添加一些预定义的位置,在UserForm_Initialize子,而不是写…

 For Each cLoc In ws.Range("LocationList") With Me.cboLocation .AddItem cLoc.Value End With Next cLoc 

…改变它

 With Me.cboLocation .AddItem "Location 1" .AddItem "Location 2" .AddItem "Location 3" 'Keep going as many as you like End With