Solved

Query in VBA  Varibles Null

Posted on 2012-04-03
7
393 Views
Last Modified: 2012-06-27
Ok, I'm having my feel of VBA.

What I'm trying to achive is use the varible data to fill in an Excel form from a Query in a loop.

The varibles that are in the 'Form' are updating the Excel Cells ok but the varibles from the query are not.  The loop does the number of records that the query is looking at but the varibles are Null(blank).  I'm sure it is something easy that I am doing wrong....  This is the code:
 
Dim strsql As String
Set db = CurrentDb
Set rs = db.OpenRecordset("qryContactsToEmail", dbOpenDynaset, dbSeeChanges)
If Not rs.RecordCount = 0 Then
rs.MoveFirst
Do Until rs.EOF

' Fill in Form
 
    Set appExcel = New Excel.application
    appExcel.Visible = True
     
    Set wbook = appExcel.Workbooks.Open("C:\temp\ABCD Template.xls")
    Set wsheet = wbook.Worksheets("ABCD")
   
    With wsheet
        .Range("B6").Value = number   < ------------------------   Comes from form, ok.
        .Range("G6").Value = SupplierCompany < -----------   This is in my query but blank
        .Range("G7").Value = Supplierid  < ----------------------   This is also in my query but blank
0
Comment
Question by:CompTech810
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 61

Accepted Solution

by:
mbizup earned 100 total points
ID: 37802771
Try this:

        .Range("B6").Value = number   < ------------------------   Comes from form, ok.
        .Range("G6").Value = rs!SupplierCompany < -----------   This is in my query but blank
        .Range("G7").Value = rs!Supplierid  < ----------------------   This is also in my query but blank
0
 
LVL 61

Expert Comment

by:mbizup
ID: 37802810
You should also add the following line to the top of any of your code modules (right under Option Compare Database in Access VBA):


Option Explicit


This will help you nip problems like this one in the bud.  Since you hadn't prefixed your fields with rs!, they were being seen as undeclared variables - defaulting to null/blank.

Option Explicit would cause a compile error in a case like this, instead of allowing the code to run with unknown/undeclared variables (which in turn cause unexpected/undesired results as you are seeing)
0
 
LVL 45

Expert Comment

by:aikimark
ID: 37802893
Please note that if you are looping through your recordset, your code (as written) is always going to populate the same cells.  I don't think that is what you are trying to do.

* if you only want the first record, you don't need to loop
* if you only want the last record, you don't need to loop.  Use a .MoveLast method
* if populating multiple rows, you will need to change your cell references.
0
Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

 
LVL 45

Expert Comment

by:aikimark
ID: 37803016
If the number doesn't change, you might populate the cells from the recordset, using the CopyFromRecordset method instead of looping.

Example:
Public Sub PushToRange()
    Dim cn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim rng As Range
    Dim lngNumber As Long
    cn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)};" & _
"Dbq=" & "C:\Users\Mark\Documents\db1.mdb" & ";"
    cn.Open
    lngNumber = 42
    rs.Open "Select " & lngNumber & ", ID, [Sample Time] From BMS1 Where ID <10", cn, 3, 3
    Set rng = ActiveSheet.Range("G6")
    Application.ScreenUpdating = False
    rng.CopyFromRecordset rs
    Application.ScreenUpdating = True
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub

Open in new window


Note:
* this transfers a block of data, starting in the upper left corner as a starting cell.
* you could transfer the numbers to the B column after the transfer or just set the B cells' value = number (if the number value doesn't change)
* You might want to read my Fast Data Push to Excel article:
http:/A_2253-Fast-Data-Push-to-Excel.html

Example:
Public Sub PushToRange()
    Dim cn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim rng As Range
    Dim lngNumber As Long
    cn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)};" & _
"Dbq=" & "C:\Users\Mark\Documents\db1.mdb" & ";"
    cn.Open
    lngNumber = 42
    rs.Open "Select ID, [Sample Time] From BMS1 Where ID <10", cn, 3, 3
    Set rng = ActiveSheet.Range("G6")
    Application.ScreenUpdating = False
    rng.CopyFromRecordset rs
    
    Set rng = ActiveSheet.Range("B6")
    Set rng = ActiveSheet.Range(rng, rng.Offset(rs.RecordCount - 1))
    lngNumber = 42
    rng.Value = lngNumber

    Application.ScreenUpdating = True
    
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub

Open in new window

0
 
LVL 2

Author Comment

by:CompTech810
ID: 37803049
aikimark:  Thanks for the information!!  It is creating a new excel speadsheet each time and emailing.
0
 
LVL 2

Author Closing Comment

by:CompTech810
ID: 37803056
I knew it had to be something easy that I was missing.  Thanks for the additional information on Option Explicit
0
 
LVL 61

Expert Comment

by:mbizup
ID: 37803066
Glad to help out :)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

You need to know the location of the Office templates folder, so that when you create new templates, they are saved to that location, and thus are available for selection when creating new documents.  The steps to find the Templates folder path are …
This article describes a method of delivering Word templates for use in merging Access data to Word documents, that requires no computer knowledge on the part of the recipient -- the templates are saved in table fields, and are extracted and install…
Using Microsoft Access, learn some simple rules for how to construct tables in a relational database. Split up all multi-value fields into single values: Split up fields that belong to other things into separate tables: Make sure that all record…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question