我很難從用戶表單上的先前記錄中正確復制特定欄位資料。我沒有要顯示的代碼示例,但我的要求非常簡單。
目前,在 12 個欄位中,我有 6 個我經常重復資料。我可以單擊并按 Ctrl '(“在上一條記錄中插入同一欄位中的值”),它會執行我想要的任務。但是,它會為任務增加大量時間。我只是想撰寫 VBA 代碼來對這些特定欄位執行該命令。
我一直無法SendKeys上班。DLast似乎有時會提供隨機資料。我覺得這應該是一個非常簡單的請求,但由于某種原因,我沒有找到一個實用的解決方案。
uj5u.com熱心網友回復:
不要擺弄陣列或查詢 - 使用DAO 的力量:
Private Sub CopyButton_Click()
CopyRecord
End Sub
- 如果選擇了一條記錄,請復制它。
- 如果選擇了新記錄,則復制最后(上一個)記錄。
Private Sub CopyRecord()
Dim Source As DAO.Recordset
Dim Insert As DAO.Recordset
Dim Field As DAO.Field
' Live recordset.
Set Insert = Me.RecordsetClone
' Source recordset.
Set Source = Insert.Clone
If Me.NewRecord Then
' Copy the last record.
Source.MoveLast
Else
' Copy the current record.
Source.Bookmark = Me.Bookmark
End If
Insert.AddNew
For Each Field In Source.Fields
With Field
If .Attributes And dbAutoIncrField Then
' Skip Autonumber or GUID field.
Else
Select Case .Name
' List names of fields to copy.
Case "FirstField", "AnotherField", "YetAField" ' etc.
' Copy field content.
Insert.Fields(.Name).Value = Source.Fields(.Name).Value
End Select
End If
End With
Next
Insert.Update
Insert.Close
Source.Close
End Sub
RecordsetClone順便說一句,這也是記錄集的 the和 the之間差異的一個很好的例子Clone——第一個是“表單的記錄”,而第二個是獨立副本。
這也意味著,表單將自動并立即更新。
uj5u.com熱心網友回復:
假設它是一個簡單的表格來編輯一個簡單的表格,并且系結的資料欄位名稱與控制元件名稱匹配,您可能會逃脫
If Me.Recordset.AbsolutePosition > 0 Then
With Me.Recordset.Clone()
.AbsolutePosition = Me.Recordset.AbsolutePosition - 1
Dim control_name As Variant
For Each control_name In Array("field1", "field2", "field3", "field4", "field5", "field6")
Me.Controls(control_name).Value = .Fields(control_name).Value
Next
End With
End If
您將其分配給同一表單上的單獨按鈕。
uj5u.com熱心網友回復:
你已經在這里發布了一個好主意。
您也可以說在插入事件之前放置一個函式。此事件僅在您開始輸入新記錄時觸發,并且它會變臟。
所以,也許是這樣:
Private Sub Form_BeforeInsert(Cancel As Integer)
Dim rstPrevious As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT TOP 1 * FROM tblPeople ORDER BY ID DESC"
Set rstPrevious = CurrentDb.OpenRecordset(strSQL)
' auto file out some previous values
If rstPrevious.RecordCount > 0 Then
Me.Firstname = rstPrevious!Firstname
Me.LastName = rstPrevious!LastName
End If
End Sub
還有一些好主意,比如要設定一個控制元件/欄位的“串列”或“陣列”,這樣您就不必撰寫很多代碼。(如此處的其他帖子/答案中所建議)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/485920.html
上一篇:使用MS-AccessVBA查找OFFICE365Build版本
下一篇:需要復制/粘貼結果所在的行
