Results 1 to 4 of 4

Thread: [RESOLVED] Write Query Loop on Excel worksheet in VBA module

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jan 2009
    Posts
    93

    Resolved [RESOLVED] Write Query Loop on Excel worksheet in VBA module

    Is it possible to set up and write SQL query on a worksheet? loop thru the record set and insert data onto another worksheet in the same file. If so, please show me a sample snippet on how to set it up in the VBA modules.

  2. #2
    PowerPoster
    Join Date
    Dec 2004
    Posts
    25,618

    Re: Write Query Loop on Excel worksheet in VBA module

    http://support.microsoft.com/kb/257819
    check out this article from microsoft
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Jan 2009
    Posts
    93

    Re: Write Query Loop on Excel worksheet in VBA module

    I am getting an error when it gets to the oCm.Execute line for some reason. Can you please look at my code and see if I am missing something. I am using ADO 2.8 library refrences in the excel VBA module.

    vb Code:
    1. Dim Cn As ADODB.Connection '* Connection String
    2.     Dim oCm As ADODB.Command '* Command Object
    3.     Dim iRecAffected As Integer
    4.            
    5. '   On Error GoTo ADO_ERROR
    6.    
    7.     Set Cn = New ADODB.Connection
    8.    
    9.     DBPath = "S:\Common\DialerExtracts\KAUFFMAN\dialer_result_last6attempts.mdb"
    10.     Cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & DBPath
    11.    
    12.     Cn.ConnectionTimeout = 40
    13.    
    14.     Cn.Open
    15.    
    16.     Set oCm = New ADODB.Command
    17.    
    18.     oCm.ActiveConnection = Cn
    19.  
    20.      SQL$ = "INSERT INTO tbl_results (record_num) VALUES (" & record_num & ")"
    21.            
    22.      oCm.CommandText = SQL$
    23.    
    24.       oCm.Execute

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Jan 2009
    Posts
    93

    Re: Write Query Loop on Excel worksheet in VBA module

    I figured out what was wrong. I was getting a primary key error, once I added in the error checking. Marked as resolved.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width