How to pass parameters to vb.net menu form at run time - vb.net

As per #jmcilhinney, rewriting request/question from scratch.
I have a code for a form with listboxes (Vb.net) which can be viewed at this link:
Multiple Selections from Listbox to rename Folders
I would like to know if it is possible to store the variables, for example, folderPath, in a text file and have them read as the form loads rather than have them hardcoded in my vb code. I actually have 5 listboxes currently and other variables, for example folderPath, folderPath2. From my limited experience programming, I've been able to pass variables in an ini file to a simple c# program. It is incredibly simple and requires 1 line of code per variable. I'm asking if this can also be done in VB.net, then how the ini or config or appsetting or xml file would be designed (its structure) and finally how i would read those variables from the text file and assign them to my code. This would allow me to change folder paths and other variables from a text file rather than opening VS, editing the paths, and recompiling.
Code says: Folderpath = MyFolderPath
Ini file has: MyFolderPath = "c:/myfolders"
Project at runtime is then: Folderpath= "c:/myfolders"

Solution credited to #jmcilhinney. From the Project Menu in Visual Studio, select Settings.
Under Name, I gave a path variable the name MyPath.
Under Type, selected String since it's text.
Under Scope I selected User as it is just for personal use.
Under Value I put in the path that I wanted to assign. You enter the path without quotations mark. For example, C:\MyApp\Myfolders.
In the VS code, Form1.vb in my project, you declare the variable this way:
Dim folderPath = My.Settings.MyPath
This is the desired alternative to the hard-coded
Dim folderPath = "C:\MyApp|Myfolders"
Notice in VS Settings we don't use quotations marks, whereas in the VB code we do use quotation marks around path. So in summary, Dim folderPath = My.Settings.MyPath is the VB code to replace Dim folderPath = "C:\MyApp|Myfolders"
The last step is to go the folder where your .exe is and open the file with the .config extension. In that file, you will see these tags, under the closing tag for userSettings. Once more the path does not have quotation marks. Note: this .config file was generated by VS when compiled (build).
<ModMenuR1.My.MySettings>
<setting name="MyPath" serializeAs="String">
<value>C:\MyApp|Myfolders</value></startup>
</setting>
</ModMenuR1.My.MySettings>
Now we can change the path variable, MyPath, in the value tag without Visual Studio, without recompiling, just by editing the .config file. This allows me to repurpose the form menu displayed in the image. A batch file could also be used to swap .config files just before run time. The actual project and config file will have at least 5 path variables.

Related

VB.NET open a Text File within the same folder as my Forms without writing Full Path

I found a similar question but it was 5 years 8 months old, had 2 replies and neither worked for me (VB.Net Read txt file from current directory)
My issue is that when I use the following code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Username_And_Password_Raw.txt")
Dim usernameAndPassword = Split(fileReader, ",")
I get an error saying:
System.IO.FileNotFoundException: 'Could not find file 'C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows\Username_And_Password_Raw.txt'.'
I have tried using all the different Applications.BLANKPath options I can find (ie; StartupPath, CommonAppDataPath, etc.) and they all return essentially the same error only with a different location.
This is the folder layout of my TXT File - I know it's a terrible, incredibly insecure and generally awful way of storing login information but this is just for a NEA so will never ever actually be used
This is the actual path of the TXT File if it helps
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\Username_And_Password_Raw.txt
The startup path is where your exe is located. That and all supporting files get copied to a binary directory when you compile in visual studio, in your case
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows
But what you're trying to do, reference the file where it sits in your solution, is probably not the best way to do it, and your code above will work (with a change, will mention later) if you change the properties of the file in the solution.
Right click on the file in the Solution Explorer Username_And_Password_Raw.txt, select Properties. Modify Copy to Output Directory to either Copy always / Copy if newer, depending on your requirement. Now that file will copy to the same directory your exe is in, and the code above should work.
Note, when creating a path, don't use string concatenation because you may have too many or too few \; use Path.Combine:
Dim filePath = Path.Combine(Application.StartupPath, "Username_And_Password_Raw.txt"
Dim fileContents = My.Computer.FileSystem.ReadAllText(filePath)

Word VBA Documents.Open deleting files in folder when falsely passing that folder's path instead of file path

I encountered the following issue:
When accidentally passing a folder path to the Documents.Open function in VBA Word I get the runtime error 5174 as one would expect.
However all files with names that begin with an underscore get deleted in that moment from that folder.
To replicate:
Assume folder C:/Test/
In said folder have two files:
test.txt
_test.txt
In Word VBA execute the command:
Documents.Open("C:/Test/")
(As part of a subroutine or in the immediate window.)
Result: Runtime Error 5174 and _test.txt is now missing.
Note: Passing a nonexisting file like "C:/Test/abc.txt" or a wrong folder path like "C:/Test" (without the last slash) will not have this effect and won't cause the runtime error.
I have only tested this on one system on a network drive under windows 10 with Microsoft Professional Plus 2019. It's entirely possible that it's an issue with the file system. Does anyone have any suggestions as to why is this happening? I now included the workaround to check if I'm passing a folder, but it's still unnerving.
The Documents.Open method opens the specified document and adds it to the Documents collection. It is designed to take the file path, not a folder. If you want to allow users to pick file(s) you may consider using the file open dialog. The FileOpenDialog triggered by your code which opens a folder for picking files allows specifying file formats that should be supported and visible via the dialog window.
Set dlgSaveAs = Application.FileDialog(msoFileDialogFilePicker)
dlgSaveAs.Filter = "Text Files (.txt)|*.txt|Word Documents (.docx)|*.docx|Word Template (.dotx)|*.dotx|All Files (*.*)|*.*"
dlgSaveAs.ValidateNames = true
Res = dlgSaveAs.Show

VBA store path including Environ("username") in a text file

I am trying to create a text file that stores a folder path. This text file is then referenced via a vba sub. The path I want to use is something like:
"C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Templates"
This works fine in the sub but I've tried all kinds of variations in the text file but none of them get recognised and trigger error 52 - bad file.
Is there a way to make this work? I'm trying to allow people to set a different file path without needing to modify the code.
If you are trying to provide a path to the folder where user templates are stored then you could try
ActiveDocument.AttachedTemplate.Path
as an alternative (returns the path to the folder where the current template is stored for the user).
Otherwise store the path template as something like
"C:\Users\###UserName###\AppData\Roaming\Microsoft\Templates"
Which gives you a single string to retrieve. Then you can use the VBA Replace function to change the ###UserName### to the value of Environ("UserName)"
my_user_path = replace(my_path_template, Environ$("UserName"))
You might also want to explore using either a CustomDocumentProperty, or a Variables, to store your path template as this keeps the path template string as part of the Document or Template and not in a separate file.

VBA Dynamic Save As, Microsoft Project to Excel

I am trying to create a macro that will export a Microsoft Project file into an excel file. Through the use of macro recording I have got a line of code that accomplishes this using the export wizard, but I want the file path and file name to be dynamic so I can use this macro on different projects. I have been searching many other threads and the Microsoft website with no luck. Is this possible?
Here is what I have:
sub formatAndSave ()
FileSaveAs Name:="C:\Users\XXXXXX\SharePoint\Projects\ProjectType\HxH\myProject.xlsx",_
FormatID:="MSProject.ACE", map:="myMap"
end sub
One idea I tried was:
Active.Workbook.SaveAs FileName:=Title
Any help would be very much appreciated!
For the sake of simplicity, let's assume for all answers below your project is located at c:\projects\myProj.mpp
I think you're after the string replace function. Something like:
Dim excelFilePath As String
excelFilePath = Replace(ActiveProject.FullName, ".mpp", ".xlsx")
Debug.Print excelFilePath
'the output would be c:\projects\myProj.xlsx
If you're unfamiliar with string manipulation in VB/VBA, just search the web for "VBA string manipulation". Microsoft has a decent article here: https://msdn.microsoft.com/en-us/library/aa903372(v=vs.71).aspx
A few other things that may be handy for you are these variables:
ActiveProject.FullName 'shows full path & name, so you'd get "c:\projects\myProj.mpp"
ActiveProject.Path 'shows just the path, so you'd get "c:\projects\"
ActiveProject.Name 'shows just the file name, so you'd get "myProj.mpp"
Finally, one caveat I've seen is that the ActiveProject.FullName and ActiveProject.Name variables may or may not provide the file extension depending on your local windows environment settings. I've observed that if Windows Explorer is configured to hide file extensions, then these variables also withhold the extension; if Explorer is configured to show them, then they are provided in the variables. Make sure your code is robust to both cases, or make sure you have control over the environment where you code will run.

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.