vba help - take count from Recordset into variable

Mallesh23

Well-known Member
Joined
Feb 4, 2009
Messages
976
Office Version
  1. 2010
Platform
  1. Windows
Hi Team,

I am tyring to Filter the data via sql Query , and take the count and store into variable.
Below is the code I am trying which works but store output into Range("a2")



VBA Code:
Sub CopyData()
    Dim Conn As New ADODB.Connection
    Dim Rst As New ADODB.Recordset
    
    FilePath = ThisWorkbook.FullName
    connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FilePath & _
                    ";Extended Properties=""Excel 12.0 Macro;HDR=YES"";"
    
    Conn.Open connstr
Dim  Cnt as long
    
   ' Sql = "Select * from [Sheet1$] order by State Desc"   
   'Sql = "Select State,city from [Sheet1$] "   
  Sql = "SELECT COUNT(State)FROM [Sheet1$] where State = ""Maharashtra"""

    
    Rst.Open Sql, Conn
    
    MsgBox Rst.RecordCount   'Getting -1 as recordset
    
    Sheets.Add
    
    Range("A2").CopyFromRecordset Rst   'Getting 3 as Correct output in Range "A2" 
           

End Sub

Below is the table

StateCity
MaharashtraPune
MaharashtraMumbai
MaharashtraNagpur
GujaratAhmedabad
GujaratSurat
KarnatakaBangalore


Thanks
mg
 

Excel Facts

What is the last column in Excel?
Excel columns run from A to Z, AA to AZ, AAA to XFD. The last column is XFD.
Try this.
VBA Code:
lngCount = Rst.Fields(0).Value
 
Upvote 0
Hi Norie,

it worked ! thanks a lot!

one more query...... Can I replace Fields(0) with Actual header name.?. to get same output.


lngCount = Rst.Fields(0).Value


Thanks
mg
 
Upvote 0
What would you change it to? You aren't specifying an alias for COUNT(State) in the query.
 
Upvote 0

Forum statistics

Threads
1,223,229
Messages
6,170,881
Members
452,364
Latest member
springate

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