Solved

Query in VBA  Varibles Null

Posted on 2012-04-03
7
383 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
  • 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
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 
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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

A simple tool to export all objects of two Access files as text and compare it with Meld, a free diff tool.
Preparing an email is something we should all take special care with – especially when the email is for somebody you may not know very well. The pressures of everyday working life stacked with a hectic office environment can make this a real challen…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Basics of query design. Shows you how to construct a simple query by adding tables, perform joins, defining output columns, perform sorting, and apply criteria.

829 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