Code With Mark
Home
About
Resources
Contact

How Easily Use SQL Statement In Excel

Learn how you can easily use sql code in excel.

VBA Code

Sub create_sheets()
    
    Sheets.Add.Name = "gender"
    Sheets.Add.Name = "country"
     
    get_data ("gender")
    get_data ("country")
End Sub
Sub get_data(sheet_name As String)

   

    '--- Declare Variables to store the connection, the result and the SQL query
    Dim connection As Object, result As Object, sql As String, recordCount As Long
    
    '--- Connect to the current datasource of the Excel file
    Set connection = CreateObject("ADODB.Connection")
    With connection
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .ConnectionString = "Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & _
        "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
        .Open
    End With
    
    
    Dim d1, r1 As Long
   
   'get the last row with data
    r1 = Worksheets(sheet_name).Cells(Rows.Count, 1).End(xlUp).Row
    
    'clear old content
    Worksheets("country").Range("A2:h" & r1).ClearContents
    'Worksheets("country").Range("A2:h").ClearContents
    
   
     'get the last row with data
    d1 = Worksheets("data").Cells(Rows.Count, 1).End(xlUp).Row
    
    '--- Write the SQL Query
    If sheet_name = "country" Then
        
        sql = "SELECT * FROM [data$a1:h" & d1 & "] where country_code='US' "
        
    ElseIf sheet_name = "gender" Then
        
        sql = "SELECT * FROM [data$a1:h" & d1 & "] where gender='Male' "
        
    End If
    
    
    '--- Run the SQL query
    Set result = connection.Execute(sql)
    
    
   
    'copy header
    Sheets("data").Range("1:1").Copy Sheets(sheet_name).Range("1:1")
    
    
   recordCount = 1
    
    '--- Fetch information
    Do
        
        Dim i As Integer

        For i = 0 To 7
             
            Worksheets(sheet_name).Cells(recordCount + 1, i + 1).Value = result(i)
        Next i
        
        'insert data > id
        'Worksheets("country").Cells(recordCount + 1, 1).Value = result(0)
          
       
        result.MoveNext
        recordCount = recordCount + 1
       
    Loop Until result.EOF
    
    
End Sub

Create newsletter web app with google sheet for FREECreate newsletter web app with google sheet for FREE←Previous
Best Way To Build A Readme Doc Site For Your ProjectBest Way To Build A Readme Doc Site For Your ProjectNext→

Related Posts

  • How Google Developers Think (And Why You Should Too)
  • Add Google Sign-In in 2 Minutes
  • Easily Import Excel File Into Microsoft Access Via VBA

Top Posts Viewed

Using JavaScript Window Onload Event Correctly
13.6K views
Learn To Create YouTube Video Downloader
6.14K views
Easily Edit HTML Table Rows Or Cells With jQuery
3.92K views

Categories

Courses
Excel
Google Script
Javascript
jQuery
Microsoft Access
MongoDB
Node JS
PHP
Quick Tip
Uncategorized
Wordpress