2017-10-14 27 views
0

我對宏很陌生,但有一些基本的想法,它是如何工作的或者能夠編寫小的VBA代碼。在USERFORM VB查詢中添加預定義的值

我已經創建了一個示例用戶窗體,但我想知道如何將值放入代碼本身內,以便我不想維護單獨的查找表以保留所有這些值,以便在我的USERFORM下創建下拉選項。

請找到我使用的代碼。

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 

I learn how to set this userfrom from a web site and you can use this link to download the sample excel file (posted on that website)

請幫我在這。

由於提前

+0

你已經用這行'Me.cboPart.Value ='「'設置了一個控制值....只是使用相同類型的代碼來設置非空白的值 – jsotola

回答

1

比方說,你想添加一些預定義位置,在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 
+0

謝謝Rosetta,它運行良好,wi你能幫我多一點,是否可以使用這些值來保存我所擁有的excel文件。如果你能幫助我,這將會很棒。 –

+0

當然。要將組合框中選定的位置放入Excel電子表格範圍(例如單元格A1)爲'Range(「A1」)= me.cboLocation.value' – Rosetta

+0

謝謝,但是我們使用用戶窗體捕獲的值,如何獲取這些值在我們創建的模塊上,例如,我從UserFomr創建的'cboLocation'下選擇一個值,然後添加一個按鈕,如果用戶單擊它,調用MODULE 1,其中代碼爲'SUB Try1()Dim location Location = cbolocation MsgBox位置END SUB'。我試過這個,但我在msgbox下獲得了空值。 –

相關問題