MS Access return function to vbs - ms-access

i'm trying to "compile" an Access ADP file to obtain an ADE with a small vbs script.
Option Explicit
Const acCmdMakeMDEFile = 603
Const msoAutomationSecurityLow = 1
Dim AccessADP
Set AccessADP = CreateObject("Access.Application")
AccessADP.AutomationSecurity = msoAutomationSecurityLow
AccessADP.visible=false
AccessADP.OpenCurrentDataBase(SourceOfADP)
I need to call one sub and one function which are written inside the ADP...for the sub no problem
AccessADP.Run "nameOfTheSub"
but i'm not able to use the function (that has to return one numeric value).
The Access function is very simple
public function getValue() as Integer
getValue=10
end function
none of these solutions works for me
dim returnValue
set returnValue = AccessADP.Run "getValue"
dim returnValue
returnValue = AccessADP.Run "getValue"
any ideas to catch the return value from the function from vbs?
thanks in advance

As you want to
get the return value of a function
expect a non-object return value
use
dim returnValue
returnValue = AccessADP.Run("getValue")
mark the param list () - see here - and the missing Set - see here.

Related

Show image using function

I'm new to VB. NET so please bear with me. In the code below, I have a picture box in my main form and I want the selected query profile_picture to show in the picture box but I have no idea what the function should return
Public Sub ShowPicture(ByVal username As String)
user = username
Dim dsSearch As DataSet
ModuleQuery.Showpic(username)
Dim dSearch As Byte() = DirectCast(dr("Photo"), Byte())
Dim ms As New MemoryStream(dsSearch)
prof_pic.Image = Image.FromStream(ms)
End Sub
This is a module which includes all SELECT queries so that it won't be messy.
I want to call a function but I don't know what to return so that I can show the image
Public Function Showpic(ByVal user As String)
Dim FunctionErrorState As Boolean = False
Dim InsertError As Boolean = False
Dim CloseError As Boolean = False
Dim dsData As New DataSet
Dim bite As Byte()
Try
openDB()
'MyADOConnection.Open()
Dim myQuery As String = "SELECT profile_picture FROM coa.register WHERE username = '" & user & "'"
Dim myCommand As New MySql.Data.MySqlClient.MySqlCommand(myQuery)
dr = myCommand.ExecuteReader
bite = DirectCast(dr("Photo"), Byte())
Catch ex As MySql.Data.MySqlClient.MySqlException
InsertError = True
End Try
Try
MyADOConnection.Close()
Catch exclose As MySql.Data.MySqlClient.MySqlException
CloseError = True
End Try
If InsertError Then
FunctionErrorState = True
End If
Return bite 'I just put something random here since I don't know what to retun
End Function
It looks to me like the image is being stored as a byte array in the database. You (i guess correctly) read this array from the database with the command bite = DirectCast(dr("Photo"), Byte()) in your ShowPic function. A byte array is just a large blob of data in memory, that you later query with the MemoryStream.
Therefore your ShowPic function (which is more a GetPic function ;-) should return Byte()
Public Function Showpic(ByVal user As String) As Byte()
You should initialize bite with Nothing
Dim bite As Byte() = Nothing
That way if an error occurs, the array will be nothing and you can check for that.
In order to convert the byte array, that contains the raw image data into an image you correctly use a MemoryStream and the Image.FromStream method. I/O in .NET works in large portions with streams. They are just a way to continously feed data from some source. In this case the source is just the memory, in particular the Byte array you got from the database.
You however never use that Byte array. Assign the result of the ShowPic function to a variable, in order to use it:
Public Sub ShowPicture(ByVal username As String)
user = username
Dim ImageData As Byte() = ModuleQuery.Showpic(username)
If ImageData IsNot Nothing Then
Using ms As New MemoryStream(ImageData)
prof_pic.Image = Image.FromStream(ms)
End Using
Else
'Your function returned nothing, so an error occured.
'This is a very crude way of error handling, since you never
'see the error in the first place, which makes debugging a
'nightmare. There are better ways, out of scope of this answer.
MessageBox.Show("No image retrieved due to an error :(")
End If
End Sub
That way you retrieve the image data from the database (again, rename it to GetPic or GetImageData or something) in ShowPic and return its raw data to the ShowPicture method where you decode and show it.

VBA Acess Function - Return Outlook Folder/Inbox as object

Private OutlookApp, Nms As Object
Sub TestSub()
Dim Fold As Object
Set OutlookApp = GetObject(, "Outlook.Application")
Set Nms = OutlookApp.GetNamespace("MAPI")
Set Fold = outlookFolderpath("Test Folder")
For Each Email In Fold.Items ' This loop doesnt work
Debug.Print Email.Subject
Next
End Sub
Private Function outlookFolderpath(Inbox As String) As Object
Dim fold_name As String
Set OutlookFolder_Path = Nms.Folders(Inbox).Folders("Inbox")
For Each Email In OutlookFolder_Path.Items ' This Loop works
Debug.Print Email.Subject
Next
End Function
Hello,
I was hoping someone could help me with the above code. I'm trying to Set and inbox folder path from a function and using it within the sub.
It works fine from within the function but not when setting it in the sub?
Can anyone see where I am going wrong? I get a runtime error '91' - Object variable or With block variable not set
so I would gather that the function is not returning the object but I'm not sure why?
thanks
You need to return the object from the function, so
Set OutlookFolder_Path = Nms.Folders(Inbox).Folders("Inbox")
should be
Set outlookFolderpath = Nms.Folders(Inbox).Folders("Inbox")
If you declare Option Explicit at the top of your code you will be less likely to run into problems like this as all your variable should be declared.

Pulling results from one function into another function

I am using Access 2010. How do I get the information in a recordset from one function moved into a different function? The following code is giving me an object variable not set error:
Function Main()
Dim rs as DAO.RecordSet
Dim i as integer
Set rs = QueryResults(i)
Do While Not rs.EOF
debug.print rs!result
rs.MoveNext
Loop
End Function
Function QueryResults(i as Integer) as DAO.RecordSet
Dim stQuery as String
Dim rsResults as DAO.RecordSet
Dim i2 as Integer
i2 = i
stQuery = "Select query that uses i2 to get results"
Set rsResults = CurrentDb.OpenRecordset(stQuery)
End Function
I can step through and see that the QueryResults function is working. I can print out each line from rsResults and see that it has what I want. The problem comes when the code hits the "do while not rs.EOF" line. It says that rs was never set to anything.
What am I doing wrong? Both functions are in the same module. It seems like it shouldn't be that hard to get results from one function into another function.
When you want a function to return something, you must assign that something to the function name.
Change the last part of your QueryResults function to this:
'Set rsResults = CurrentDb.OpenRecordset(stQuery)
Set QueryResults = CurrentDb.OpenRecordset(stQuery)
End Function

VBA: Returning A Worksheets Object Reference From A Function

How do I return a Worksheets Object Reference? I've been perusing through various Google searches with nada results.
For example, I have a functioning code like so. wSheet already dim'ed:
Public wSheet As Worksheet
...
Set wSheet = ActiveWorkbook.Worksheets("ExampleSheet")
wSheet.Range("A1").Value = "Hello"
However, I want wSheet to now call a module that supplies it to the correct reference. Something like this:
Public wSheet As Worksheet
...
Set wSheet = myModule.get_ExampleSheet
wSheet.Range("A1").Value = "Hello"
And then have a function in module myModule
Function get_ExampleSheet() As Worksheets
get_ExampleSheet = ActiveWorkbook.Worksheets("ExampleSheet")
End Function
Everything I try gives me various runtime errors. Is there anyway to get this to work?
Thanks and advance!
You are returning the wrong type of object in your function.
Function get_ExampleSheet() As Worksheets
get_ExampleSheet = ActiveWorkbook.Worksheets("ExampleSheet")
End Function
This currently has several errors.
Function get_ExampleSheet() As Worksheet
Set get_ExampleSheet = ActiveWorkbook.Sheets("Sheet1")
End Function
Note I changed:
Return type to Worksheet (you are trying to set a variable, wSheet, which is of type Worksheet to a Worksheets type variable)
Added set keyword
Changed to .Worksheets to .Sheets to return the specific sheet you are interested in
Sub Lookup()
Dim state As Variant
Dim PodName As Variant
Set state = ThisWorkbook.Worksheets("Sheet1").Range("E:E")
Sheets("Sheet1").Activate
PodName = WorksheetFunction.VLookup(state, Range("A1:C55"), 2, False)
ThisWorkbook.Worksheets("Sheet1").Range("F:F") = PodName
End Sub
Macro should stop once the target cell is blank
In order to return an Object from a function, you need to provide the Set keyword:
Function get_ExampleSheet() As Worksheet
Set get_ExampleSheet = ActiveWorkbook.Worksheets("ExampleSheet")
End Function
http://excelmacromastery.com/Blog/index.php/the-complete-guide-to-worksheets-in-excel-vba/
in your regular part of the code
Dim issues_sheet As Worksheet
Set issues_sheet = create_working_sheet("Issues")
issues_sheet.Range("A1").Value = "bssssbb"
the function can be something like
Function create_working_sheet(sheet_name As String) As Worksheet
For i = 1 To Worksheets.Count
If Worksheets(i).Name = sheet_name Then
exists = True
End If
Next i
If Not exists Then
Worksheets.Add.Name = sheet_name
'if we want it at the end
'Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheet_name
End If
Set create_working_sheet = ThisWorkbook.Sheets(sheet_name)
End Function
A complete overview of the ways you can set a worksheet using VBA can be found here: http://codevba.com/excel/set_worksheet.htm

VBA custom procedure/function in Worksheet called outside its module

I've been playing with this problem for some time, and havent figured out how to do it.
I have the same function in every worksheet (and those sheets are named like this Name="One", CodeName="SheetOne" ...):
const someVar as Boolean = True
Public Function myFunction() as Boolean
myFunction = someVar
End Function
Now I want it to be called from outside like this - In ThisWorkbook there is procedure "doThis()" and function "TestThis():
Sub doThis()
Dim i as Integer
For i = 1 to ThisWorkbook.Sheets.Count
If testThis(ThisWorkbook.Worksheets(i)) = True then
Debug.print "Success!"
End If
Next i
Function testThis(x As Worksheet)
If x.myFunction = True Then
testThis = True
Else
testThis = False
End If
Now I know that at this line "If x.myFunction = True" it throws error "Method or data member not found", because i cant call that function with this reference, so I've tried it with VBComponent:
Sub doThis()
Dim i as Integer
For i = 1 to ThisWorkbook.Sheets.Count
If testThis(ThisWorkbook.VBProject.VBComponents(Worksheets(i).CodeName)) _
= True then
Debug.print "Success!"
End If
Next i
Function testThis(x As VBComponent)
If x.myFunction = True Then
testThis = True
Else
testThis = False
End If
But again, it throws an "Object does not support this property or method" error. Any ideas, How can I call that function from a variable, that has stored reference of any kind to that Worksheet? Any help would be appreciated.
When compiling the code, Excel checks to see if "WorkSheet" object type has a myFunction method - it is looking at the generic built-in Worksheet object, and this doesn't include your "add on" function (and neither does the "VBComponent" type), so it throws an error.
If you change your parameter type to Object (a more generic type) then it will compile...
Function testThis(x As Object)
testThis = x.myFunction()
End Function
I know this is an old thread but I thought I may as well share my discoveries.
Also, I suspect there is a better way to evaluate the exact same function in every sheet but, for anyone searching, here is a solution to do exactly what you asked for in the title of the post.
In your ThisWorkbook include
Const myFunction = "myFunctuion"
Public ws as Worksheet
For each ws in Me.Sheets
If testThis(ws) then Debug.print "Success!"
next ws
Function testThis(x as Worksheet)
testThis = callByName x, x.CodeName & "." & myFunction
End Function