vba,ms-access,access-vba,ms-access-2007 , Is there a more efficient way to display multiple query results in different text boxes on a Form


Is there a more efficient way to display multiple query results in different text boxes on a Form

Question:

Tag: vba,ms-access,access-vba,ms-access-2007

I have a form with several different text boxes. Each text box is populated with the result of a different query. I'm not very familiar with VBA / Access (I am teaching myself) and am not sure if what I'm doing is the most efficient. I was hoping someone could suggest maybe a less cumbersome way of populating text boxes on a form with different queries, or perhaps even suggest a better variable naming convention.

*edit - I think there is a way to place a formula directly in a text box rather than doing it through VBA but I received a #name error.

Private Sub Form_Load()
Dim db As DAO.Database
Dim qdf As QueryDef
Dim rst As Recordset

Dim qdf2 As QueryDef
Dim rst2 As Recordset

Set db = CurrentDb()

Set qdf = db.QueryDefs("QryGetTotalTransactions")
Set rst = qdf.OpenRecordset

Set qdf2 = db.QueryDefs("QryGetTotalTransactionsInManagement")
Set rst2 = qdf2.OpenRecordset

[Form_Portfolio Status].TotalTransaction_txt.Value = rst![Total]
[Form_Portfolio Status].TotalInManagement_txt.Value = rst2![Total]

End Sub

Answer:

In each of those two examples, you're retrieving a single value from a saved query. So DLookup could get the values with less code.

DLookup("[Total]", "QryGetTotalTransactions")
DLookup("[Total]", "QryGetTotalTransactionsInManagement")

You could assign the DLookup return value to a text box's .Value property ... like you were doing with the recordset value. Or you could use the DLookup expression as the text box Control Source.

Regarding efficiency, DLookup performance is not likely to be faster than the recordset approach. But you wouldn't need all that code to manage DAO objects. So perhaps there could be savings in developer time, which should count for something. :-)


Related:


EXCEL VBA: How to manupulate next cell's (same row) value if cell.value=“WORD” in a range


excel,vba,excel-vba
I want to change the next cell in same row in a if cell.value="word" in a range. I have defined the range, using 'for' loop. In my code, if cell.value="FOUND THE CELL" then cell.value+1="changed the next right side cell" cell.value+2="changed the second right side cell" end if I know this...

Find column with unique values move to the first column and sort worksheets


excel,vba,excel-vba,sorting
I have 2 worksheets with the same headers in different orders. Headers are I.D, Name, Department, Sales, Start date, End Date and a few others. What I am aiming to do is search through the workbooks in which the headers may be in different orders, find the column which has...

Excel 2013 Add a Connector Between Arbitrary Points on Two Different Groups


excel,vba,excel-vba
I'm working in Excel 2013 to (programmatically) add a straight line connector between the lower right hand corner of a rectangle that is part of a grouped shape with the endpoint of a grouped series of line segments. As it stands, I can't even seem to do this manually on...

Update query when database in ms access


c#,ms-access
My update query update tbl_Clients set [email protected], [email protected] where [email protected] When I am updating this code in giving error Syntax error in update statement...

Excel-VBA: create named Range in row until end of cell content


vba,excel-vba,range
Imagine an Excel sheet with some rows and some content in each row (i.e. different column-length for each row). In Excel-VBA: How can I create a range-X within column-X that goes from row-cell-2 to the end of the content of this X-column ?? i.e. I would like to create a...

Using date in CreateQueryDef


vba,date,ms-access
I have a table on which I run a query that I export to Excel. Here is an example: Table: Food Item | Price | Limit_Date | ------------------------------- Carrot | 0.80 | 08/07/2015 | Salmon | 4.30 | 01/07/2015 | Biscuits | 2.40 | 15/12/2015 | Milk | 1.00 |...

VBA “Compile Error: Statement invalid outside Type Block”


excel,vba,excel-vba,excel-2010
I am running a VBA Macro in Excel 2010 with tons of calculations, so data types are very important, to keep macro execution time as low as possible. My optimization idea is to let the user pick what data type all numbers will be declared as (while pointing out the...

Formatting specific part of text string in VBA


excel,vba,excel-vba,outlook,format
I am in process of creating a macro that will save the current workbook, create a new outlook message and attach the file to the message. My macro does that but I can not format the text in the body of the email to my liking. Dim OutApp As Object...

Removing Alert When Using DeleteFile API


vb.net,vba,api,delete
I'm writing a VBA application which involves looping a large number of directories recursively. I am using the FindFirstFile API to to achieve this, as it offers a substantial performance boost over the FileSystemObject. In order to remove the FSO from my code entirely, I need a routine to delete...

Iterate Databases and Delete Query


ms-access,access-vba
I am trying to iterate a table with database names in it, open the database, check if a query exists, if it does delete it, then import a query from the database this code is being executed from. I keep getting a compile time error on the line of Set...

Using VLOOKUP formula or other function to compare two columns


mysql,excel,vba,date
I have one table like this: SHORT TERM BORROWING 1/6/2009 94304 12/31/2010 177823 6/30/2011 84188 12/31/2011 232144 6/30/2012 94467 9/30/2012 91445 12/31/2012 128523 3/31/2013 83731 6/30/2013 78330 9/30/2013 70936 12/31/2013 104020 3/31/2014 62345 6/30/2014 62167 9/30/2014 63494 12/31/2014 104239 3/31/2015 69056 I have another column which lists each date from...

Extract All Named Ranges Into A Class


vba,excel-vba
I have a workbook with a very large amount of named ranges (well over 200). I really need a way to work quickly and easily with all of the named ranges so I can then work with / populate them using VBA. My solution up until now has been to...

Label linked to a text box value


excel,vba,textbox,label
Good morning, I am editing an User Form on VBA Excel and I would like to show an alert if the user insert a certain value in a text box. I wrote this code: If txtbox.Value < 0 Then lbl_Alert.Visible= True Else lbl_alert.Visible=False End IF The code works properly but...

Excel Search VBA macro


excel,vba,excel-vba
I have been given the task of searching through a large volume of data. The data is presented identically across around 50 worksheets. I need a macro which searches through all these sheets for specific values then copies certain cells to a table created in a new workbook. The macro...

Add 1 to datediff result if time pass 14:30 or 2:30 PM


sql,ms-access,ms-access-2007
Here is my SQL query which returns number of days by subtracting current date from specified date and returns exact as i need, but in addition i want to add 1 to result if current time passes 14:30 or 2:30. My query SELECT reservations.customerid, DateDiff("d",reservations.checkin_date,Now()) AS Due_nights FROM reservations Am...

Excel VBA User-Defined Function: Get Cell in Sheet Function was Called In


excel,vba,excel-vba,user-defined-functions
I have a user-defined function in Excel that I run in multiple sheets. I am trying to use Cells(i, j) to pull the value of cells by their row and column in the sheet in which my function is called. Instead, Cells(i, j) pulls the value of cell [i,j] in...

Sort multiple columns of Excel in VBA given the top-left and lowest-right cell


excel,vba,excel-vba,sorting
I am trying to sort these three columns (Sort By Col-2) in excel using VBA. Top-left (Row number and Column number e.g. 1,1) and lowest-right cell (Row number and Column number e.g. 9,3) are known. Every cell contains the values of String type. Input: Col-1 Col-2 Col-3 P1 I1 XYZ...

Finding position of a particular string containing cell in Excel


excel,vba
I am searching for a string using below code For x = 2 To lastrow If Sheets("sheet1").Cells(x, 3) = TFMODE Then ....... 'TFMODE is the string discussed 'This particular string "TFMODE" is randomly recurring throughout 'sheet in column 3. I need to know position for a particular string in sheet1...

Get work time in minutes based on shift schedule


sql,sql-server,sql-server-2008,ms-access,user-defined-functions
In production we have 3 shifts. Each Shift timing is described in table tbl_ShiftSched: WT - work time, PT - break time. ShiftTmID - schedule for 2 and for 3 shifts. I am looking for easy way to get work time in minutes having start and end time. For example,...

VBA data type to store Range().Characters()


vba
I can't find a data type to store Characters from a Range. I already tried the following code, but nothing happened. I think the problem is because of wrong data type. Dim chars As Characters chars = Range("A2").Characters(0, 4) MsgBox chars.Text ...

I need help setting the RecordSource of a Report within a VBA Function


vba,ms-access,access-vba
Ok, so I've been looking around here for a few days (and a few other sites) and while I have modified my code a good bit to find a solution, it still doesn't work. I have four source queries, and I'd like to set the record source of my report...

Activecell not in Array


vba
Having difficulty comparing my activecell against a predefined array. After importing data from another source I want to trim out the columns I don't need I've trued the array as both undefined, string and variant And tried activecell / activecell.value <> NeededColumns No joy :( Sub Trim() Dim NeededColumns As...

VBA how to initialize vCPath


vba,excel-vba,excel-2010
How do I initialize vCPath? VBA Run-Time Error 1004 @Garry's Student says I "must somehow use the info you get from Application.FileDialog(msoFileDialogOpen) to generate the full filespec of the file you wish to open". What's the simplest way to do this? I am a VBA beginner: I have been programming...

excel search engine using vba and filters?


excel,vba
I am using the following vba code to filter my rows in excel based on the value in my cell C5 Sub DateFilter() 'hide dialogs Application.ScreenUpdating = False 'filter for records that have June 11, 2012 in column 3 ActiveSheet.Range("C10:AS30").AutoFilter Field:=1, Criteria1:="*" & ActiveSheet.Range("C5").Value & "*" Application.ScreenUpdating = True End...

Converting ADODB Loop into DAO


excel,vba,ms-access,ado,dao
Hi I've been developing a vba project with a lot of help from examples here. I'm trying to access a MS Access database from Excel VBA and import large data sets (500-100+ rows) per request. Currently, the following loop works using ADODB however, the Range("").Copyfromrecordset line is taking very long...

adding variables into another variable vba


excel,vba,excel-vba
Dim x As Long Dim y As Long Dim CDTotal As Double Dim CSTotal As Double Dim ETotal As Double Dim FTotal As Double Dim HTotal As Double Dim ITotal As Double Dim ITTotal As Double Dim MTotal As Double Dim TTotal As Double Dim UTotal As Double Dim TotalValue...

If cell value starts with a specific set of numbers, replace data


excel,vba,excel-vba
My cell values are strings of numbers (always greater than 5 numbers in a cell, ie 67391853214, etc.) If a cell starts with three specific numbers (ie 673 in a cell value 67391853214) I want the data in the cell to be replaced with a different value (if 673 are...

Userform is not unloading once command button is pressed


vba,excel-vba
Having a little trouble with my userform, its not unloading once i hit the command button the data is inputted to the sheet but the userform is not refreshed and the data stays in the text boxes. It was working fine until i put the data validation in, but i...

How to create a date using strings in vba?


vba,ms-access,access-vba,ms-access-2003
I want to run a for-loop from sometime to some specific time. Let's say from the first day of the year to the last day: I am given the year and I need to add the month and the day to it: I am trying to concatenate into a full...

Replace reference with its value in Excel VBA workbook


vba,excel-vba
I have an Excel workbook to manage my Delivery Notes, which creates another workbook with actual delivery note and stores it in the folder for me, then places new record in my main workbook so that the Delivery Number for the next delivery note can be increased by 1. My...

embed object and display as icon in word document?


vba,ms-word,word-vba
I have a word document. In the word document I have command button. What I am after is when the user presses the command button it would open a dialog box so that the user can embed a file and display as an icon within the word document. How WOULD...

Referencing a new inserted column Excel VBA


excel,vba,excel-vba
I am trying to reference a cell in the below formulaes. 'AUA Summary'!$D$9 . Each time the macro runs a new column D is inserted. The Problem: When the column is inserted my reference moves to ** 'AUA Summary'!$E$9. How do I get to reference 'AUA Summary'!$D$9 even if a...

Compare two data sets in different sheet and print difference in other sheet using excel VBA?


excel,vba
I have two data sets in two different sheet Sheet1 is my Orginal ref and sheet2 is for comparison. sheet2 data should get compared by Sheet1 and print entire mismatched row of sheet2 and highlight the cells which has mismatch data and this difference should be printed with column header...

for-loop add columns using SQL in MS Access


sql,ms-access,table,for-loop,iteration
I am trying to add n columns to a table, like in this example of code where n = 10: Sub toto() Dim db As Database, i As Integer Set db = CurrentDb() For i = 1 To i = 10 db.Execute " ALTER TABLE time_series " _ & "ADD...

Interface Controls for DoEvent in Excel


excel,vba,excel-vba,loops,doevents
I have a macro to loop through a range and return emails to .Display based on the DoEvents element within my module. I iterate that: row_number = 1 'And Do DoEvents row_number = row_number +1 'Then a bunch of formatting requirements Loop Until row_number = 'some value I am wondering...

ByRef Argument type mismatch on just changing the variable position in declaration


vba,byref
I have defined a function in VBA as follows: Sub TestFunction() Dim ArrayLength, IDvariable, IDComparisonResult, PreArrayLength As Integer ReDim NodesArray(0) PreArrayLength = 0 IDvariable = 0 . . Sort PreArrayLength End Sub whereas the function called is as follows: Sub Sort (PreArrayLength As Integer) . . . end sub Above...

Right function vba


vba,excel-vba
I want to take everything to the right of the symbol in the string I used Right(enclosedValue, InStr(enclosedValue, "*") - 0) where enclosed value is 29,6 *60, so I need it to return *60, but now it returns ,6 *60 Sorry if this question has been asked already, I have...

Creating a Range in VBA


vba,range
I'm working on my first VBA function. The goal is to have a function that accepts two integers as inputs, and outputs an array containing all the integers in between the two inputs (end-points included). Example: If I input 5 and 9, the output should be an array of 5,...

How do I get a cell's position within a range?


excel,vba,excel-vba
How would I go about getting the relative position of a cell within a range? Finding the position of a cell in a worksheet is trivial, using the Row- and Column-properties, but I am unsure of how to do the same within a range. I considered using the position of...

Copying a Range from Excel and Pasting it into Powerpoint NOT as a metafile but as a table which you can edit in PPP


vba,excel-vba,powerpoint-vba
All I want to do is copy a range from Excel and then paste this range into PowerPoint. When my range is manually copied from Excel to the clipboard... If I right click on a blank slide when pasting into PowerPoint, it gives me the option to paste "using destination...

Excel VBA Program Code by Using Randomize Timer


vba
What is wrong in below program code, why not returning correct result. Whenever i put any number in excel cell (1,1) and run the program, Numbers changed automatically, also not throwing a correct result in cell (1,2). Please Help as i learning VBA. Private Sub Sheet2_1() Dim num1 As Integer...

Copying sheet to last row of a sheet from another workbook


excel,vba,excel-vba
I'm stuck in this block of code that copies sheet("Newly Distributed") to the last row of sheet("Source") from another workbook. The error is runtime error 9. What's wrong with my code? Any response would be appreciated. Private Sub copylog3() Dim lRow As Long Dim NextRow As Long, a As Long...

VBA - Unable to pass value from Private to Public Sub


excel,vba,excel-vba
I have a tool which I am designing to present a number of questions to a user in a set of userforms. The form will generate a score via passing an integer result from the userform to a main sub, which passes the code to a worksheet. My problem is...

How do you delete favorite folders in outlook using VBA


vba,outlook-2007
I wish to delete all the folders from the outlook favorites then subsequently replace them, but the delete doesn't seem to work. What's wrong with my code. Setup Objects works fine ' Get the "Favorite Folders" navigation group Set favGroup = Application.ActiveExplorer.NavigationPane.Modules.GetNavigationModule(olModuleMail).NavigationGroups.GetDefaultNavigationGroup(olFavoriteFoldersGroup) This works Set inboxFldr = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox) favGroup.NavigationFolders.Add (inboxFldr)...

Exit Sub And Call another Sub


vba,excel-vba,call
I have two subs, sub1 and sub2. I want to exit sub1 completely and start sub2 if a condition is satisfied. My attempt is (running from : sub1 . . If x=y Then Exit Sub And Call sub2 End If . . End Sub ...

How do I do to count rows in a sheets with filters? With a suppress lines


excel,vba,filter
I have a sheet with lots of columns, but when I filter and use count = Application.WorksheetFunction.CountA(Range("A:A")) It returns all the rows non Empty. Not only the rows I filtered....