Pass SQL Result to VBA Variable

xljunkie

Board Regular
Joined
May 20, 2011
Messages
92
Can someone please help me? I'm trying to count the distinct instances in a field and just store that number in a vba variable. I can create queries in Access and save this info in a table, and then DLOOKUP, but that seems too convoluted.

Code:
SELECT Count(FieldA) FROM (SELECT DISTINCT FieldA FROM tblExample)
 

Excel Facts

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
Nevermind figured it out.

Code:
strSQL = "SELECT Count(FieldA) as A FROM (SELECT DISTINCT FieldA FROM tblExample)"
    Set rs = CurrentDb.OpenRecordset(strSQL)
    Variable = rs!A
 
Upvote 0
Also possible is using DCount (without the need for recordsets):
Code:
Sub foo()
    Dim x As Long
    x = DCount("*", "Table1")
    Debug.Print x
End Sub
 
Upvote 0

Forum statistics

Threads
1,221,831
Messages
6,162,248
Members
451,756
Latest member
tommyw

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top