从http://www.techrepublic.com/blog/how-do-i/how-do-i-start-an-access-label-report-with-any-label-on-the-sheet/ 的说明开始
接下来我将其修改为三个文本框而不是一个。它们被命名为“txtStart”、“txtEnd”、“txtLabelPos”。为该表单使用下面的代码。
注意 SQL 中的“WHERE”子句...更改表/字段名称以满足您自己的需要。
Option Compare Database
Option Explicit
Private Sub cmdCancel_Click()
'Reset and take no further action.
Me!txtStart.Value = 1
End Sub
Private Sub cmdPrint_Click()
'Pass table with label data, position for first label, and label report.
Dim bytPosition As Variant
Dim bytCounter As Byte
Dim rst As New ADODB.Recordset
If IsNull(Me.txtStart) Or Me.txtStart = "" Then
MsgBox "You must enter a starting range for the data.", vbOKOnly + vbCritical, "Missing Start Range"
Exit Sub
End If
If IsNull(Me.txtEnd) Or Me.txtEnd = "" Then
MsgBox "You must enter an ending range for the data.", vbOKOnly + vbCritical, "Missing End Range"
Exit Sub
End If
If IsNull(Me.txtLabelPos) Or Me.txtLabelPos = "" Or Not IsNumeric(Me.txtLabelPos) Then
MsgBox "You must enter the starting label position to print on.", vbOKOnly + vbCritical, "Missing Label Position"
Exit Sub
End If
Set rst.ActiveConnection = CurrentProject.Connection
rst.Open "SELECT * FROM tblCustomerLabels" _
, , adOpenDynamic, adLockOptimistic
'Delete previous label data.
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE FROM tblCustomerLabels"
'Add one empty record for each missing label.
bytPosition = Nz(Me!txtLabelPos.Value, 0)
For bytCounter = 2 To bytPosition
rst.AddNew
rst.Update
Next
'Update label data.
Dim strSQL As String
strSQL = "INSERT INTO tblCustomerLabels ( Company, [Last Name], [First Name], Address, City, [State/Province], [ZIP/Postal Code], [Country/Region] ) " & _
"SELECT Customers.Company, Customers.[Last Name], Customers.[First Name], Customers.Address, Customers.City, Customers.[State/Province], Customers.[ZIP/Postal Code], Customers.[Country/Region] " & _
"FROM Customers " & _
"Where [Last Name] >= '" & Me.txtStart & "' AND [Last Name] <= '" & Me.txtEnd & "';"
DoCmd.RunSQL strSQL
'Open label report.
DoCmd.SetWarnings True
DoCmd.OpenReport "rptCustomerLabels", acViewPreview
rst.Close
Set rst = Nothing
Exit Sub
errHandler:
MsgBox Err.Number & ": " & Err.Description, vbOKOnly, "Error"
rst.Close
Set rst = Nothing
DoCmd.SetWarnings True
End Sub