Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
A bookmark is a system-generated Byte array that uniquely identifies each record. The DAO Bookmark property of a Recordset object changes each time you move to a new record. Para identificar um registro, vá até ele e atribua o valor da propriedade Bookmark do DAO a uma variável do tipo Variante. Para retornar o registro, defina a propriedade Bookmark do DAO como o valor da variável.
O exemplo de código a seguir mostra como encontrar o produto que gera mais e menos receita por categoria usando um indicador para salvar a posição de registro atual. Com um marcador, você pode executar outras operações no objeto Recordset e retornar à posição do registro salvo.
Sub GetProductStats()
Dim dbsNorthwind As DAO.Database
Dim rstProducts As DAO.Recordset
Dim rstCategories As DAO.Recordset
Dim varFirstMark As Variant
Dim varHighMark As Variant
Dim varLowMark As Variant
Dim curHighRev As Currency
Dim curLowRev As Currency
Dim strSQL As String
Dim strCriteria As String
Dim strMessage As String
On Error GoTo ErrorHandler
Set dbsNorthwind = CurrentDb
strSQL = "SELECT * FROM Products WHERE UnitsOnOrder >= 40 " & _
"ORDER BY CategoryID, UnitsOnOrder DESC"
Set rstProducts = dbsNorthwind.OpenRecordset(strSQL, dbOpenSnapshot)
If rstProducts.EOF Then Exit Sub
StrSQL = "SELECT CategoryID, CategoryName FROM Categories " & _
"ORDER BY CategoryID"
Set rstCategories = dbsNorthwind.OpenRecordset(strSQL, dbOpenSnapshot)
' For each category find the product generating the least revenue
' and the product generating the most revenue.
Do Until rstCategories.EOF
strCriteria = "CategoryID = " & rstCategories![CategoryID]
rstProducts.FindFirst strCriteria
curHighRev = rstProducts![UnitPrice] * rstProducts![UnitsOnOrder]
If Not rstProducts.NoMatch Then
' Set bookmarks at the first record containing the CategoryID.
varFirstMark = rstProducts.Bookmark
varHighMark = varFirstMark
varLowMark = varFirstMark
' Find the product generating the most revenue.
Do While rstProducts![CategoryID] = rstCategories![CategoryID]
If rstProducts![UnitPrice] * rstProducts![UnitsOnOrder] > _
curHighRev Then
curHighRev = rstProducts![UnitPrice] * _
rstProducts![UnitsOnOrder]
varHighMark = rstProducts.Bookmark
End If
rstProducts.MoveNext
Loop
' Move to the first record containing the CategoryID.
rstProducts.Bookmark = varFirstMark
curLowRev = rstProducts![UnitPrice] * rstProducts![UnitsOnOrder]
' Find the product generating the least revenue.
Do While rstProducts![CategoryID] = rstCategories![CategoryID]
If rstProducts![UnitPrice] * rstProducts![UnitsOnOrder] < _
curLowRev Then
curLowRev = rstProducts![UnitPrice] * _
rstProducts![UnitsOnOrder]
varLowMark = rstProducts.Bookmark
End If
rstProducts.MoveNext
Loop
End If
' Set high and low bookmarks to build the message string.
strMessage = "CATEGORY: " & rstCategories!CategoryName & _
vbCrLf & vbCrLf
rstProducts.Bookmark = varHighMark
strMessage = strMessage & "HIGH: $" & curHighRev & " " & _
rstProducts!ProductName & vbCrLf
rstProducts.Bookmark = varLowMark
strMessage = strMessage & "LOW: $" & curLowRev & " " & _
rstProducts!ProductName
MsgBox strMessage, , "Product Statistics"
rstCategories.MoveNext
Loop
rstProducts.Close
rstCategories.Close
dbsNorthwind.Close
Set rstProducts = Nothing
Set rstCategories = Nothing
Set dbsNorthwind = Nothing
Exit Sub
ErrorHandler:
MsgBox "Error #: " & Err.Number & vbCrLf & vbCrLf & Err.Description
End Sub
Um indicador será útil se um método falhar porque a posição de registro atual está indefinida. A propriedade LastModified do objeto Recordset fornece uma boa ilustração de como usar um indicador. A propriedade LastModified retorna o marcador do último registro do Recordset a ser adicionado ou modificado. Para usá-la, defina a propriedade DaO Bookmark igual à propriedade LastModified , da seguinte maneira.
rstCustomers.Bookmark = rstCustomers.LastModified
Isso move a posição do registro atual para o último registro adicionado ou modificado. Isso é particularmente útil ao adicionar novos registros; pois, depois de você adicionar um novo registro, o registro atual será aquele no qual estava antes da adição. Com a propriedade LastModified, você pode ir para o registro recém-adicionado, se essa for a ação esperada por seu aplicativo. Quando você fecha um objeto Recordset, qualquer marcador salvo torna-se inválido.
Não é possível usar um marcador de um Recordset em outro , mesmo que ambos os objetos Recordset estejam baseados na mesma tabela ou consulta de base. No entanto, você pode usar um indicador no clone de um Recordset, conforme mostrado no exemplo a seguir.
Dim dbsNorthwind As DAO.Database
Dim rstOriginal As DAO.Recordset
Dim rstDuplicate As DAO.Recordset
Dim varBookMark As Variant
Set dbsNorthwind = CurrentDb
' Create the first Recordset.
Set rstOriginal = dbsNorthwind.OpenRecordset("Orders", dbOpenDynaset)
' Save the current record position.
varBookMark = rstOriginal.Bookmark
' Create a duplicate Recordset.
Set rstDuplicate = rstOriginal.Clone()
' Go to the same record.
rstDuplicate.Bookmark = varBookMark
rstOriginal.Close
You can also use the DAO Bookmark property on the Recordset object underlying a form. With this property, your code can mark which record is currently displayed on the form, and then change the record that is being displayed. For example, on a form containing employee information, you may want to include a button that a user can click to show the record for an employee's supervisor.
Observação
Dynasets com base em determinadas tabelas vinculadas, como tabelas paradoxais que não têm chave primária, não dão suporte a indicadores nem fazem objetos Recordset de tipo avançado. You can determine whether a given Recordset object supports bookmarks by checking the value of the Bookmarkable property.
Suporte e comentários
Tem dúvidas ou quer enviar comentários sobre o VBA para Office ou sobre esta documentação? Confira Suporte e comentários sobre o VBA para Office a fim de obter orientação sobre as maneiras pelas quais você pode receber suporte e fornecer comentários.