An Easy VBA Counter

This post is actually based on a question I received on my YouTube video:

https://www.youtube.com/watch?v=l5Aj8dPH8KY&lc=z234unjqmpymudvjp04t1aokgbwgqi4nrfxkozk3u00rrk0h00410

The counter can be implemented a bit easier by using VBA.

Here’s how:

Sub AddCounter()

    Dim intCounter As Integer
    Dim strSQL As String
    Dim strSQLUpdate As String
    
    Dim rst As Recordset
    
    'counter is done based on the sort order
    'strSQL = "SELECT CustomerID, counter FROM Customers ORDER BY City DESC"
    
    strSQL = "SELECT CustomerID, counter FROM Customers ORDER BY CompanyName"
    
    
    Set rst = CurrentDb.OpenRecordset(strSQL)
    
    rst.MoveFirst
    intCounter = 1
    
    Do Until rst.EOF
         
        'update the counter column as the counter variable increases:
        strSQLUpdate = "UPDATE Customers SET counter=" & intCounter & " WHERE CustomerID='" & rst("CustomerID") & "'"
        CurrentDb.Execute strSQLUpdate
        
        intCounter = intCounter + 1
        rst.MoveNext
    Loop
    
    rst.Close
    Set rst = Nothing
    
    'alert us when were are done
    MsgBox "Complete"
End Sub

That’s it. Questions?




By the way, if you got or are getting value from the VBA information, please give me a tip, thanks!


These posts may help answer your question too...

How To Parse A Flat File In Excel VBA

In another post I demonstrated how to access a file on your computer using the MS Office Library. Here it is if you don’t know what I’m talking about. In this post, I am going to show you how to access the file and load it into your spreadsheet. I will do the same thing […]

How can I interact with other Office applications (Excel) using VBA in Access?

Need to write your Access data or query to an Excel file? Here is the how to do it: Most people are familiar with Excel and know how to use it well (enough), and when you start talking about Access, they get scared off, and don’t know what to do anymore. Well, here you are […]

How To Generate A XML File With Access VBA

XML is used to structure your data. You can send a CSV file to another person, but using XML, you can structure your data in a more elegant format, and get very specific about your fields, and what data is contained within your tags (your field names). This is different than a basic CSV file […]

Mouse Click Counter On Access Form

This post will demonstrate how you can count the number of clicks on your button in a certain time frame. It will function like a game . Here is the database form all in one: Option Compare Database Public m_dteStartTime As Date Public m_dteStopTime As Date Private Sub btnClicker_Click() Dim intValue As Integer Dim rst […]

Previous Post

How To Use Access VBA To Copy A Table With DoCmd.CopyObject

Next Post

Why Does My Query Change Like To Alike?