pass variable from excel to access - excel

I have a VBA code in Excel that ask the user where an .xls file is a make something with that file.
What I'd like to do now is to pass the name of the file (myFile) to VBA code that I have in Access, in order to update a table with that file and other fields.
In VBA Excel, the name of the Sub is: Sub UpdateSupplier(myFile As String)
What is the code that I should use in VBA Access in order to use myFile?

Try this: Declare your variable myFile as public, that means not write:
Dim myFile in your Excel Sub,
but write instead
Public myFile in the Declare Section of the module.
Then create a new Function in this module, which only gives back this public variable myFile:
function GiveMemyFile() as string
GiveMemyFile = myFile
end function
Now you can call this function from Access to get the value of myFile.

think I found the solution now, it's so simple if you found it:
Your 'Makro' in Excel should look like this:
function Test (ByRef strFilename)
strFilename = yourFilename
end function
The first 'trick' is, to use a ByRef Parameter 'strFilename' to give back your Filename.
Now in Access you can use:
strNewFilename = ""
xl.Run "Test", strNewFilename
Debug.Print strNewFilename
and you will see the filename the Excel Macro wrote in the variable.
I have tested this and it worked fine for me. Good luck!

Related

How to save Dictionary object to bin file in VBA?

This is VBA case. I want to save Dictionary object to bin file and put it again back to Dictionary later. This object should be the only content of bin file. In general I am stuck on:
Compile error: Can not Get or Put an object reference variable or a
variable of user-defined type containing an object reference
Relevant part of code looks like this:
Public generalListOfAddIns As Object
Public Type BinaryCapsuleType
forObject As Object
End Type
Public Sub CreateGeneralListOfAddIns()
Set generalListOfAddIns = CreateObject("Scripting.Dictionary")
End Sub
Public Sub SaveDictAsBin()
Dim Capsule As BinaryCapsuleType
Set Capsule.forObject = generalListOfAddIns
Dim filePath As String
Dim fileNo As Integer
Dim loadedGeneralListOfAddIns As Object
filePath = "C:\TestFolder\ListOfAddIns.bin"
fileNo = FreeFile
Open filePath For Binary Lock Read Write As #fileNo
Put #fileNo, , Capsule
Close #fileNo
End Sub
I tried and didnt helped:
Both early binding and late binding
Save Dictionary direcly
Encapsulate Dictionary using the Type statement (as in code example)
I would like to avoid:
Saving Dictionary content into text files
Transforming Dictionary into Array for saving purpose
Adding more references into VBA Project
Which sources didnt helped me (or I dont understand them):
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/can-t-get-or-put-user-defined-type-containing-object-reference
https://analystcave.com/excel-saving-your-vba-data/
Thank you very much for any help or ideas, RosMane

Unable to create simple VBA function in Excel Macro and call it

I'm trying to create a macro that can collect data from an excel spreadsheet in the local active workbook and then create header file which I would later incorporate into my project. But for the life of me I must be missing something so DUMB that I can't create a working function that returns a string (which would construct a C++ structure) to the calling function. I've simplified the example code to is absolute bare minimum to isolate the problem but I still cannot figure out what I'm doing wrong. I'm not an expert at VBA but I know how to create code and I can't narrow down what VBA is unhappy about. I keep getting "compile error, syntax error." Please copy the following code into your module and see if compiles properly for you. If you know where I went wrong please let me know. Much Appreciated!!!
Sub CREATE_FACTORY_SETTING_HEADER()
Dim FS, TSsource
Set FS = CreateObject("Scripting.FileSystemObject")
Dim TSout
Set TSout = FS.Createtextfile("HeaderFile.h", True)
Dim fileHeading As String
fileHeading = "File Heading for Header file"
Dim fileBody As String
fileBody = "Some initial file body lines"
fileBody = fileBody & createStructBody
TSout.Write fileHeading & fileBody
TSout.Close
End Sub
Public Function createStructBody() As String
Dim structBody As String
structBody = "Hey I'm a struct body, but I can't be returned for some reason"
Return structBody
End Function
Both VBA and VBScript use 'assignment to function' (instead of 'return' or 'result of last statement') to return results from functions. So
Public Function createStructBody() As String
createStructBody = "Hey I'm a string and can be returned."
End Function

how to I use functions in vba from my personal macro workbook?

I have the following function in my personal workbook:
Public Function Get_Rows_Generic_personal(sheet_name As String) As Long
Get_Rows_Generic = Worksheets(sheet_name).UsedRange.Rows.Count
End Function
How do I call it from a module in another project?
This thread was supposed to have the answer but the link is dead.
You have two choices really:
You can use Application.Run; or
You can set a reference to the VBA project of your personal macro workbook ( but you'll need to change the name of the project from the default 'VBAProject' first). Once you have a reference set, you can call the function directly
To use Application.Run you pass the workbook and routine name as the first argument, then any arguments required by that routine as additional arguments to Run. If the routine name is the same as its parent module, or you have more than one routine in the workbook with the same name, you need to supply the module name too, and if the workbook name contains spaces, you need to enclose it in single quotes. So the basic syntax is either:
Application.Run "'workbook name.xlsm'!routine_name", parameter1
or:
Application.Run "'workbook name.xlsm'!module_name.routine_name", parameter1
For example:
dim lCounter as long
lCounter = Application.Run("'Personal.xlsb'!Get_Rows_Generic_personal", "some sheet")

Excel VBA - Use an existing string in called sub

I'm pretty new to this so apologies in advance
I'm half way through a userform in Excel and I'm trying to cut some fat off my code by using Call - I have 12 buttons that all do the same thing, the only difference is that each buttons sub is dependant on the buttons caption. My problem is that I can't figure out a way to use a String I've already declared in the Buttons Sub, then use it in the called Sub. I know you can do it, but my googling skills have failed me :(
Please could someone show me how to do this? Hope that all makes sense...
Here is a very small snippet of my code, but you get the jist:
Public Sub CommandButton4_Click()
Dim Name As String
Name = CommandButton4.Caption
Call Sort1
End Sub`
And the other one (Also tried this as function for the sake of trial and error)
Public Sub Sort1(Name As String)
Label11.Caption = Name
Sheets(Name).Select
End Sub
What you're referring to is passing an argument to another subroutine or function. Let's say you want to use a function a lot of times to get the first letter of a string. A sample of this is:
Function LeftOne(StrSample As String) As String
LeftOne = Left(StrSample, 1)
End Function
The above function can be used inside another function or subroutine provided you meet its requirement: StrSample. By declaring StrSample As String in the arguments field of the function, you are basically requiring that any calls to this should require a string to be passed to it. Anything else would throw an error.
The full line LeftOne(StrSample As String) As String can be read as: "I am function LeftOne. Pass me a string and I'll return to you a string after doing something with it." Note that the name StrSample is an arbitrary name.
Anyway, calling the above is as simple as:
Sub MsgInABox()
Dim StrToFeed As String
StrToFeed = "BK201"
MsgBox LeftOne(StrToFeed) 'Returns B.
End Sub
In your example, if you want to pass Name to Sort1, your attempt is absolutely correct.
Let us know if this helps.
You hat to give your sort1 procedure the parameter name.
call sort1(name)
or
call sort1(CommandButton4.Caption)

Excel VBA global variables "lifetime"?

Sorry about the non descriptive Title, I just didn't know how to describe my goal.
I'm new at VBA and didn't yet understand how things really work.
I've written a function which gets a directory from the user, and displays data from the first file in the directory. Now, I want to add a "next" button.
When the "next" button is pressed, my code should display data from the next file in the directory.
I tried to use global variables but they seem to get initialized each time the button is pressed.
What is the best way to achieve my goal? Do I have to use the spreadsheet as memory and write and read everything from there? Or does Excel VBA have some other "live memory" mechanism?
Thanks,
Li
Globals will not normally be reinitialized when you click a button. They will be reinitialized if you recompile your VBA project. Therefore, while debugging, you may see a global being reinitialized.
You can use the spreadsheet as memory. One way to do this is to have a worksheet whose Visibility property you set to xlSheetVeryHidden (you can do this from the VBA project). This worksheet won't be visible to users, so your VBA application can use it to store data.
This could be approached many ways, as with any problem I guess!
You could break the problem up into two subroutines:
1) Retrieve all the file names in the selected directory and display the first file's data
2) If it's not the last file, get the next file's data and display it
You could use a global variable to store the filenames and an index to remember where you are up to in the collection of filenames.
Global filenames As Collection
Global fileIndex As Integer
Public Sub GetFilenames()
Dim selectedDirectory As String
Dim currentFile As String
selectedDirectory = "selected\directory\"
currentFile = Dir$(selectedDirectory)
Set filenames = New Collection
While currentFile <> ""
filenames.Add selectedDirectory & currentFile
currentFile = Dir$()
Wend
' Make sure there were files
If filenames.Count >= 1 Then
fileIndex = 1
' Call a method to display data
DisplayData(filenames(fileIndex))
Else
' No files
End If
End Sub
Public Sub GetNextFile()
' Make sure we have a filenames object
If Not filenames Is Nothing Then
If fileIndex < filenames.Count Then
fileIndex = fileIndex + 1
' Call the display method again
DisplayData(filenames(fileIndex))
Else
' Decide what to do after reaching the final file
End If
Else
' No filenames
End If
End Sub
I didn't include the DisplayData procedure as I'm not sure what type of files you're grabbing or what you are doing with them but if it were say excel files it could be something like:
Public Function DisplayData(filename As String)
Dim displayWb As Workbook
Set displayWb = Workbooks.Open(filename)
' Do things with displayWb
End Function
You could then set the macro of the button to "GetNextFile" and it will cycle through the files after each click. As for the lifetime of global variables, they only reinitialize when the VBA project is reset or when they are specifically initialized through a procedure or the immediate window.
Perhaps these two functions can also help you:
SaveSetting
GetSetting
as showed here: http://www.j-walk.com/ss/excel/tips/tip60.htm

Resources