2014-02-15 26 views
0

我想輸入一個員工ID。一旦輸入並按下命令按鈕,它將自動使用數據庫中列出的當前數據填充用戶表單。然後,用戶可以更改任何輸入,然後「提交」將粘貼回數據庫的表單。我搜索了一下,發現了一些應該爲我想要做的事情工作的代碼,但我只是努力去理解如何使其適應我的特定需求。UserForm更新基於文本框的數據庫

Option Explicit 
Public frmName As Variant 'store row of name 
Public frmDate As Variant 'store column of date 

'Subroutine when clicking the first ("find") button 
Private Sub btnfind_Click() 
'Defining variables 
Dim pr01 As String 
Dim dt01 As Date 
Dim tsk01 As Integer 

'Assigning variables to inputs 
pr01 = UserForm1.TextBox1.Text 
dt01 = UserForm1.TextBox2.Text 
tsk01 = UserForm1.TextBox3.Text 

'Looking for Name in column "A" 
With ThisWorkbook.Worksheets("Sheet4") 
    frmName = .Columns("A").Find(pr01).Row 
End With 


'Looking for inut Date in row "1" 
With ThisWorkbook.Worksheets("Sheet4") 
    frmDate = .Rows(1).Find(CDate(dt01)).Column 
End With 

If frmName Is Nothing Or frmDate Is Nothing Then 
    'not found 
    Exit Sub 
    End If 

'Retrieving the existing number of tasks according to name and date 
'and showing number in the 'tasks' text input box in the user form 
With ThisWorkbook.Worksheets("Sheet4") 
    UserForm1.TextBox3.Text = .Cells(frmName, frmDate) 
End With 

End Sub 

'Subroutine when clicking the Second ("update") button 
Private Sub btnupdate_Click() 

'Paste updated Number of tasks in appropriate cells according to name and date 
'The new number of tasks should over write what was there previously 
With ThisWorkbook.Worksheets("Sheet4") 
    .Cells(frmName, frmDate) = UserForm1.TextBox3.Text 
End With 
End Sub 

frmName和frmDate是兩個文本框的名稱?任何幫助理解這個代碼適用於我的電子表格將不勝感激。

謝謝。

回答

0

「frmXxxxx」通常表示Xxxxx是用戶表單。這裏代碼的第2行和第3行聲明frmName和frmDate爲Variant s,並且註釋表明它們是行和列。這些確實是無益的名字。

正常情況下,保存行或列的變量將被聲明爲Long。由於使用它們的僞劣代碼,它們必須聲明爲Variant

考慮:

'Looking for Name in column "A" 
With ThisWorkbook.Worksheets("Sheet4") 
    frmName = .Columns("A").Find(pr01).Row 
End With 

If frmName Is Nothing Or frmDate Is Nothing Then 
    'not found 
    Exit Sub 
End If 

可變pr01已被設置爲UserForm1.TextBox1.Text。從評論我假設這個文本框是爲用戶輸入一個名稱。如果文本框和變量被賦予了有意義的名字,那將會很有幫助。

如果在列A中找不到pr01中的名稱,那麼Find將返回Nothing。這就是爲什麼frmName被定義爲Variant,因爲Long不能設置爲Nothing

雖然這會起作用,但它不易用戶友好或維護者友好的代碼。

除了可怕的名字,我建議是這樣的:

Public frmName As Long  'store row of name 
Dim rng as Range  ' Temporary variable 

'Looking for Name in column "A" 
With ThisWorkbook.Worksheets("Sheet4") 

    Set rng = .Columns("A").Find(pr01) 
    If rng Is Nothing Then 
    ' Tell user the name could not be found 
    : : 
    Exit Sub 
    Endif 
    frmName = rng.Row  

End With 

希望以上可以幫助你破譯這個代碼。我也希望我的代碼更容易理解。

相關問題