-1

我有多个 VBA 表单,第一个表单从组合框中获取用户名并将其保存在全局变量中,代码如下:

Option Compare Database
Public emplID_global

Private Sub OKLogin_Click()


 If Not IsNull(Me.Combo_emplID) Then
  emplID_global = Me.Combo_emplID.Column(1)
  DoCmd.Close
  DoCmd.OpenForm "NavFrm", acNormal
 End If
End Sub

现在在我的另一个表单中,我有一个组合框,我想在加载表单时自动填充该变量的值,我使用以前的表单保存,下面是代码:

Private Sub Form_Load()
 Me.AdvName = emplID_global
 Me.DataForm.Form.Recordset.MoveLast

End Sub

但它不起作用,它什么也没做。我想在所有形式中使用这种代码。

有人可以建议我的代码中的错误是什么,我对 VBA 还很陌生。提前致谢 :)

4

1 回答 1

3

Add a field to your underlying table for the owner of that particular record. (I just called it Owner.)

Add the following code to your form:

Private Sub Form_BeforeInsert(Cancel As Integer)
Owner = Environ("username")
End Sub

Private Sub Form_Current()
Dim editable As Boolean

if nz(Owner,"")="" then
    editable=true
else
    editable = (Environ("username") = Owner)
    End If

Form.AllowDeletions = editable
Form.AllowEdits = editable

End Sub

This is a fairly generic solution that does the job. Environ("username") returns the user's windows username. This is not necessarily all that secure. A person could go to the command prompt and edit the username environment variable so that they appear to be another person. This will definitely not keep out the NSA or anyone else with a little computer knowledge and bad intentions. But it will keep the honest people honest.

Explanation: The BeforeInsert runs as a new record is being saved. In this case, it sets the record's Owner field to the user's Windows username.

The OnCurrent portion runs every time a new record is displayed. The code will check to see if the current Windows username matches the username stored in the record's Owner field and set the forms AllowEdits and AllowDeletions flags accordingly. Also, if the Owner field is null (as in the case of a new record), editable will be set to true. If you wanted to really emphasize the fact that the user shouldn't be changing things, you could also enable/disable the individual text boxes...

TextBox1.Enabled=editable
ComboBox2.Enabled=editable
... etc.

Simple solution. Keeps honest people from overwriting each others' work. I use this approach a lot.

于 2017-10-15T07:54:02.317 回答