Cannot Declare String In Module VB6 - vba

I am trying to read database strings from a file for a legacy application. To do this, I place the file in the AppData folder for each user. Now, I need to tell the application where the file is. However, I cant seem to declare a string in a module (the original strings were declared as constants in this module). How can I get over this? any help would be appreciated.
This is what I tried:
Dim loc As String
loc = Environ$("APPDATA")
Public Const CnnSTR = ReadIniValue(loc & "\PensionMaster\PM-Strings.ini", "DB", "DBSQL")
But I got an 'Invalid outside procedure' error.

Tim Williams is correct. Instead of trying to declare it as a public variable create a public function, or property. My preference is to create a function in a .bas module, and a property in a class.
Public Function GetCnnSTR() As String
Dim loc As String
Dim strPath as String
loc = Environ$("APPDATA")
strPath = ReadIniValue(loc & "\PensionMaster\PM-Strings.ini", "DB", "DBSQL")
GetCnnSTR = strPath
End Function
or
Public Property Get CnnSTR() As String
Dim loc As String
Dim strPath as String
loc = Environ$("APPDATA")
strPath = ReadIniValue(loc & "\PensionMaster\PM-Strings.ini", "DB", "DBSQL")
CnnSTR = strPath
End Property

CnnSTR = ReadIniValue(Environ$("APPDATA") & "\PensionMaster\PM-Strings.ini", "DB", "DBSQL"
Will work. Maybe a Dim CnnSTR as String line as well.
Const x=5
y = X
is exactly the same as
y=5

Related

Replace a variable Environ in vba

Please, I had already create à variable Environ("MYXLSPATH")
Dim vr As String
vr = "SETX MYXLSPATH """ & ThisWorkbook.FullName & """"
Call Shell(vr)
And now, I want to replace the content of this variable by: "NAME"
Dim vr As String
Environ.RemoveItem ("MYXLSPATH")
vr = "SETX MYXLSPATH "" NAME """
Call Shell(vr)
But, It doesn't work, can you help me please ?
The second set of code should be:
Dim vr As String
vr = "SETX MYXLSPATH ""NAME"""
Call Shell(vr)
I've made two changes:
Removed the Environ.RemoveItem line. It's not needed and seems to be problematic.
Removed the space either side of NAME. So this means the environment variable is set to NAME and not  NAME 
End result:
Instead of running a CMD.EXE command you can call in to the Shell object to get to the environment variables directly. To replace, just call the set again.
Here are procedures to set and get:
Option Explicit
'#Description("Set environment variable value. Defaults to user space. System space requires elevated process to modify.")
Public Sub EnvironSetItem(ByVal environVariable As String, ByVal newValue As String, Optional ByVal strType As String = "User")
With CreateObject("WScript.Shell").Environment(strType)
.Item(environVariable) = newValue
End With
End Sub
'#Description("Get environment variable value. Defaults to userspace.")
Public Function EnvironGetItem(ByVal environVariable As String, Optional ByVal strType As String = "User") As String
With CreateObject("WScript.Shell").Environment(strType)
EnvironGetItem = .Item(environVariable)
End With
End Function

Passing String to another sub routine [duplicate]

This question already has answers here:
How to make Excel VBA variables available to multiple macros?
(3 answers)
Closed 6 years ago.
I am trying to practice embedding my code. I created a subroutine called JrnlHeader to declare variables I will use in another subroutine. I am currently only concerned with one variable named Header. I would like to know why Header is empty in subroutine PrintToTextFile and how I can fix it to be able to use strings declared in JrnlHeader.
Private Sub JrnlHeader()
Dim Header As String
Dim SeqNo As String
Dim SeqVar As String
Dim Bu As String
Dim BuVar As String
Dim JrnlID As String
Dim JrnlIDVar As String
Dim JrnlDate As String
Dim JrnlDateVar As String
Dim Descr As String
Dim DescrVar As String
Dim Ledger As String
Dim LedgerVar As String
Dim Source As String
Dim SourceVar As String
Dim CurEff As String
Dim Reverse As String
Dim AutoLn As String
Dim AdjEnt As String
Header = "<JRNL_HDR_IMP>"
SeqNo = "<SEQNO>" & SeqVar & "</SEQNO>"
Bu = "<BUSINESS_UNIT>" & BuVar & "</BUSINESS_UNIT>"
JrnlID = "<JOURNAL_ID>" & JrnlIDVar & "</JOURNAL_ID>"
JrnlDate = "<JOURNAL_DATE>" & JrnlDateVar & "</JOURNAL_DATE>"
Descr = "<DESCR254>" & DescrVar & "</DESCR254>"
Ledger = "<LEDGER_GROUP>" & LedgerVar & "</LEDGER_GROUP>"
Source = "<SOURCE>" & SourceVar & "</SOURCE>"
CurEff = "<CUR_EFFDT>" & JrnlDateVar & "</CUR_EFFDT>"
Reverse = "<REVERSAL_CD>N</REVERSAL_CD>"
AutoLn = "<AUTO_GEN_LINES>N</AUTO_GEN_LINES>"
AdjEnt = "<ADJUSTING_ENTRY>N</ADJUSTING_ENTRY>"
End Sub
Sub PrintToTextFile()
Dim FileNum As Integer
JrnlHeader
FileNum = FreeFile ' next free filenumber
'Open "C:\Temp\TEXTFILE.TXT" For Output As #FileNum ' creates the new file
Open "C:\temp\TEXTFILE.TXT" For Append As #FileNum
Print #FileNum, Header
Close #FileNum ' close the file
End Sub
You have defined Header to be a local variable in JrnlHeader. This means its scope does not extend to other subroutines/functions.
You can define the scope of the variable to be "module" level, by placing the Dim Header As String statement prior to the first subroutine/function within the code module. Then its value will be available when execution resumes in PrintToTextFile.
Alternatively, you could change your code to pass the variable as a parameter between the two functions:
Sub PrintToTextFile()
Dim Header As String
'...
JnrlHeader Header
'...
Print #FileNum, Header
End Sub
Sub JrnlHeader(Header As String)
'... (but don't include any declaration of Header!)
Header = "<JRNL_HDR_IMP>"
'...
End Sub
But, judging by how many variables are being set up in JrnlHeader, I think you will want to go with using a module-level scoped variable approach.
The two subroutines have different scope. Variables defined JrnlHeader are not available in PrintToTextFile. If you want header to be available in PrintToTextFile the change it to PrintToTextFile(header as string) and call PrintToTextFile(header) from JrnlHeader.

VB DownloadFile URL variable

I'm attempting to pass a string to the DownloadFile function in Visual Basic in place of the URL. The url will change according to what the current month and year is. Ex: http://example-website.com/092015
For this reason, I've done the following to make sure the url is updated every month:
Public Sub Main()
Dim A As String = "http://example-website.com/"
Dim B As String = Format(Month(Now), "00")
Dim C As String = Year(Now)
Dim registrySite As String = A & B & C
End Sub
The problem that I'm having is, the DownloadFile function requires a string.
Public Sub DownloadFile (
address As String,
destinationFileName As String
)
Is there a workaround for this or another way to do what I'm trying to do? I should note that the website cannot be cached.

Renaming all files in a folder

I'm wondering if it's possible to rename all the files in a folder with a simple program, using vb.NET
I'm quite green and not sure if this is even possible.
Lets say there is a folder containing the files:
Text_Space_aliens.txt, fishing_and_hunting_racoons.txt and mapple.txt.
Using a few credentials:
Dim outPut as String = "TextFile_"
Dim fileType as String = ".txt"
Dim numberOfFiles = My.Computer.FileSystem.GetFiles(LocationFolder.Text)
Dim filesTotal As Integer = CStr(numberOfFiles.Count)
Will it be possible to rename these, regardless of previous name, example:
TextFile_1.txt, TextFile_2.txt & TextFile_3.txt
in one operation?
I think this should do the trick. Use Directory.GetFiles(..) to look for specific files. Enumerate results with a for..each and move (aka rename) files to new name. You will have to adjust sourcePath and searchPattern to work for you.
Private Sub renameFilesInFolder()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim i As Integer = 0
For Each fileName As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
In your title you state something about chronologically, but within your question you never mentioned it again. So I did another example ordering files by creationTime.
Private Sub renameFilesInFolderChronologically()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim curDir As New DirectoryInfo(sourcePath)
Dim i As Integer = 0
For Each fi As FileInfo In curDir.GetFiles(searchPattern).OrderBy(Function(num) num.CreationTime)
File.Move(fi.FullName, Path.Combine(fi.Directory.FullName, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
I've never done Lambdas in VB.net but tested my code and it worked as intended. If anything goes wrong please let me know.

Declaring constant in VBA from a INI file

I have some const in a VBA module but I would like to put them in a INI file because I have other applications that use the same constants. This works:
Public Const PATH_DB As String = "\\server\folder\bdd.mdb"
This however doesn't work:
Public Const PATH_DB As String = getFromIni("path","db","C:\config.ini")
Public Function getFromIni(ByVal strSectionName As String, ByVal strEntry As String, ByVal strIniPath As String) As String
Dim x As Long
Dim sSection As String, sEntry As String, sDefault As String
Dim sRetBuf As String, iLenBuf As Integer, sFileName As String
Dim sValue As String
sSection = strSectionName
sEntry = strEntry
sDefault = ""
sRetBuf = Strings.String$(256, 0) '256 null characters
iLenBuf = Len(sRetBuf$)
sFileName = strIniPath
x = GetPrivateProfileString(sSection, sEntry, "", sRetBuf, iLenBuf, sFileName)
sValue = Strings.Trim(Strings.Left$(sRetBuf, x))
If sValue <> "" Then
getFromIni = sValue
Else
getFromIni = vbNullChar
End If
End Function
# C:\config.ini
[path]
db=\\server\folder\bdd.mdb
My getFromIni function actually works pretty well but not when I want to declare constants (it doesn't compile at all). I tried a global variable instead but for some reason, it doesn't work either, the variable cannot be found when used from another form in the same project (it only works when it's declared as a const, but I can't declare it as a const when getting the value from a function).
What's wrong?
You cannot assign a function call as the value of a CONST string. I would expect you to receive the error "Constant expression required" when running this.
Change
Public Const PATH_DB As String = getFromIni("path","db","C:\config.ini")
to
Public PATH_DB As String
Place the following call that gets the value from INI file in a initialize method (say Database Open event)
PATH_DB = getFromIni("path","db","C:\config.ini")