How to save Dictionary object to bin file in VBA? - excel

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

Related

Call helper function within parent without redefining objects from parent in the helper

I'm working in Excel with VBA to collect data for a table I'm building I have to go out to a TN3270 emulator to get it. In order to work with with the emulator I have to define a few objects to do the work. I also have a few helper functions that are used by multiple functions to navigate to different screens in the emulator. So far in order to use them I have had to copy the object definitions into those functions to get them to work. This works most of the time but occasionally (and in a way I cant predictably replicate) I get an error when the helper is recreating a particular object to use.
Option Explicit
Public Sub gather_data()
Dim TN_Emulator As Object
Dim Workbook As Object
Set TN_Emulator = CreateObject("TN_Emulator.Program")
Set Workbook = ActiveWorkbook
Dim string_from_excel As String
#for loop to go through table rows
#put value in string_from_excel
If string_from_excel = some condition
go_to_screen_2
#grab and put data back in excel
Else
go_to_screen_3
#grab and put data back in excel
End If
go_to_screen_1
#next loop logic
End Sub
Public Sub go_to_screen_1()
Dim TN_Emulator As Object
#the next step occasionally throws the error
Set TN_Emulator = CreateObject("TN_Emulator.Program")
#send instructions to the emulator
End Sub
Is there a way to import the existing objects (that get created and used without any errors) without redefining them into the helper functions to avoid this problem? I have tried searching in google but I don't think I'm using the right search terms.
First thanks goes to #JosephC and #Damian for posting the answer for me in the comments.
From JosephC 'The Key words you're looking for are: "How to pass arguments to a function".', and he provided the following link ByRef vs ByVal describing two different ways to pass arguments in the function call.
And from Damian the solution to my immediate concern. Instead of declaring and setting the objects that will be used in body of the helper function. Place the object names and types in the parentheses of the initial helper name, and when calling the helper from the other function also in the parentheses, shown below.
Option Explicit
Public Sub gather_data()
Dim TN_Emulator As Object
Dim Workbook As Object
Set TN_Emulator = CreateObject("TN_Emulator.Program")
Set Workbook = ActiveWorkbook
Dim string_from_excel As String
#for loop to go through table rows
#put value in string_from_excel
If string_from_excel = some condition
Call go_to_screen_2(TN_Emulator)
#grab and put data back in excel
Else
Call go_to_screen_3(TN_Emulator)
#grab and put data back in excel
End If
Call go_to_screen_1(TN_Emulator)
#next loop logic
End Sub
Public Sub go_to_screen_1(TN_Emulator As Object)
#send instructions to the emulator
End Sub
I believe I understood the instructions correctly, and have successfully tested this for my-self. I also passed multiple objects in the helper function definition and calls as needed for my actual application, in the same order each time Ex.
Sub go_to_screen_1(TN_Emulator As Object, ConnectionName As Object)
and
Call go_to_screen_1(TN_Emulator, ConnectionName)

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

Extracting the Company property from a Word document using Excel VBA

I'm using Excel 2010 and VBA to reorganize some Word documents on my C:\ drive and I want to pull the "Company" property of each document into a sheet containing a list of documents. The full file path of each document appears in row A (like so: "C:\folder\subfolder\file.doc"),and I would like to populate the corresponding "Company" property in row F.
I'm trying to write a macro for a custom Excel function DocCompany that will use a text string containing a local filepath to return the "Company" property of the document that the filepath identifies.
I've had better luck with the Last Modified and File Size properties, as both have dedicated VBA functions (FILEDATETIME and FILELEN, respectively). In each case, all I had to do was write a macro for a custom Excel function that returns the result of the VBA function for a file path string located in the sheet.
Given the following function, =GetFileDateTime(A1) will return the last save date for the document identified by the filepath string contained in A1.
Function GetFileDateTime(FileName As String) As Date
GetFileDateTime = FileDateTime(FileName)
End Function
Given the following function, =FileSize(A1) will return the file size in bytes of the document identified by the filepath string contained in A1.
Function FileSize(FileName As String)
FileSize = FileLen(FileName)
End Function
However, the Company property has no corresponding VBA function, so (as I said above), I want to write a macro defining a custom Excel function DocCompany that will accept a local filepath string as input and use it to output the Company property of the document.
This is what my macro looks like right now:
Function CompanyID(FileName As String) As String
CompanyID = Documents(FileName).Open
Documents(FileName).BuiltinDocumentProperties (wdPropertyCompany)
End Function
When I try to save it, Excel returns the error message "Compile error: Sub or Function not defined". Then it selects the reference to the "Documents" collection in the second row.
Why does Excel insist that I define "Documents" as a variable when every reference I can find confirms that it IS in fact an object or collection? What can I do to make this code work? Do I need to take a different approach?
Why does Excel insist that I define "Documents" as a variable when every reference I can find confirms that it IS in fact an object or collection?
Since Documents is not part of the Excel object model, it is being interpreted as a variable. You need to bind Word to the Excel instance, and reference that instance of the Word Application class.
Function CompanyID(FileName As String) As String
Dim wdApp as Object 'WOrd.Application
Dim doc as Object 'Word.Document
Const wdPropertyCompany as Long = 21 'Explicit reference for late-bound Word Application
Set wdApp = CreateObject("Word.Application")
Set doc = wdApp.Documents.Open(FileName)
CompanyID = doc.BuiltinDocumentProperties (wdPropertyCompany)
doc.Close False
End Function
Function F_snb(c00)
With GetObject(c00)
F_snb = .BuiltinDocumentProperties(21)
.Close 0
End With
End Function
in A2: G:\OF\example.docx
in D2: =F_snb(A2)

Use string variable to set object variable in VBA? (Excel 2013)

I have a number of ActiveX controls/buttons on a page, and I would like to modify several of the parameters of the buttons (in a loop function).
I am fine with writing the loop function to achieve this, but cannot find a way to refer to the object using a string variable. I have set up an object variable (as per below), and a string variable to be used to change the reference for the object variable - but can't find a way to get it to work.
This is the code that does NOT work:
Private Sub TrialCode_Click()
Dim ButtonObj As Object
Dim ButtonCaption As String
Dim ButtonString As String
ButtonString = "CommandButton1"
Set ButtonObj = ButtonString
ButtonCaption = "Something"
ButtonObj.Caption = ButtonCaption 'example of the kind of parameters I want to change
End Sub
The Set ButtonObj = ButtonString is the command that fails, reporting a Type Mismatch error.
I'm working in Excel 2013.
I really hope there is some way to do this. Any help will be really appreciated!!!
The CommandButton belongs to an OLEObject
try
ButtonString = "CommandButton1"
Set ButtonObj = ActiveSheet.OLEObjects(ButtonString)
ButtonCaption = "Something"
ButtonObj.Object.Caption = ButtonCaption 'example of the kind of parameters I want to change
Note that some properties occur directly under ButtonObj, others such as Caption sit below Object

Only user-defined type defined in public object modules can be coerced when trying to call an external VBA function

I am trying to call an Access function from Excel and get this error:
Compile Error: Only user-defined types defined in public object
modules can be coerced to or from a variant or passed to late-bound
functions.
I tried to adopt this solution I found, but with no luck. Here is my code:
In the Excel Module ExternalStatistics
Option Explicit
Public Type MyExternalStatistics
esMyInvites As Single
esMyInvitePerTalk As Single
End Type
Public MyExtRecStats As MyExternalStatistics
In the Sheet1(A-Crunched Numbers) object:
Option Explicit
Public appRecruitingAccess As Access.Application
Public Sub Worksheet_Activate()
Dim MyExtRecStats As MyExternalStatistics
Dim RecruitWindow As Integer
Dim test As String
Set appRecruitingAccess = New Access.Application
With appRecruitingAccess
.Visible = False
.OpenCurrentDatabase "C:\Dropbox\RECRUITING\Remote0\Recruiting 0.accdb"
RecruitWindow = DateDiff("d", Format(Date, Worksheets("ActivityAndIncentive").Range("IncentiveStart").Value), Format(Date, Worksheets("ActivityAndIncentive").Range("IncentiveEnd").Value))
RecruitWindow = DateDiff("d", Format(Date, Worksheets("ActivityAndIncentive").Range("IncentiveStart").Value), Format(Date, Worksheets("ActivityAndIncentive").Range("IncentiveEnd").Value))
MyExtRecStats = .Run("ExternalRecruitingStats", RecruitWindow) '*** ERROR HERE ***
.CloseCurrentDatabase
.Quit
End With
Set appRecruitingAccess = Nothing
End Sub
In the Access Module ExternalStatistics
Option Compare Database
Option Explicit
Public Type MyExternalStatistics
esMyInvites As Single
esMyInvitePerTalk As Single
end Type
Public Function ExternalRecruitingStats(StatWindow As Integer) As MyExternalStatistics
Dim MyRecStats As MyExternalStatistics
Dim Invites As Integer, Talks As Integer
Invites = 1
Talks = 2
With MyRecStats
.esMyInvites = CSng(Invites)
.esMyInvitesPerTalk = CSng(Invites/Talks)
End With
ExternalRecruitingStats = MyRecStats 'return a single structure
End Function
It does not like the MyExtRecStats = .Run("ExternalRecruitingStats", RecruitWindow) statement. I would like to eventually assign several set in the Access function and bring them all back with one object. Then I can place those values where they should be in the spreadsheet.
Type definitions in VBA are very local and they don't work well when you try to use them with objects that may not have access to the exact definition of the Type (which is probably the case here).
Sometimes, using a Class may work. You would need to make the class public and instantiate it before passing it around, but I have some doubts that it will actually work (for the same reason that the class definition won't be visible from one app to the other).
Another simple solution would be to use a simple Collection object instead, where you add your values as items to the collection. Of course the exact order of how you add/retrieve items is important.
There are a few interesting answers to a similar issue in User Defined Type (UDT) As Parameter In Public Sub In Class Module. It's about VB6 but it should also apply in great part to VBA.
Having said all this, you may be able to resolve all your issues by importing your Access code into Excel instead.
You can use DAO or ADO from Excel and manipulate Access databases just as if you were in Excel, for instance:
Connecting to Microsoft Access Database from Excel VBA, using DAO Object Model
Using Excel VBA to Export data to Ms.Access Table

Resources