UserForm基于文本框更新数据库

时间:2014-02-15 04:23:19

标签: database excel-vba userform vba excel

我正在尝试输入员工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是两个文本框的名称吗?理解此代码以应用于我的电子表格的任何帮助都将非常感激。

谢谢。

1 个答案:

答案 0 :(得分: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

我希望以上内容可以帮助您破译此代码。我也希望我的代码更容易理解。

相关问题