Declaring constant in VBA from a INI file - vba

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")

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

Program fixed functions that does not need to be initialized

I have written a function to extract a recieved token from a "xx":"..." format
Public Class HelperFunctions
Public Function ExtractToken(ByVal myToken As String) As String
'Split fields on comma
Dim fields = myToken.Split(":")
'Quote literal
Dim quote = """"c
'Use trim to remove quotes
Dim value = fields(2).Trim(quote)
Return value
End Function
End Class
But instead of initializing the function
Dim hc as New HelperFunctions
hc.ExtractToken(_string)
I want to use it straight forward
HelperFunctions.ExtractToken(_string)
I have not programmed for a while and cannot figure it out as well as come up with the name of this type of functions to find a tutorial.
You need to declare the Function as Shared:
Public Class HelperFunctions
Public Shared Function ExtractToken(ByVal myToken As String) As String
'Split fields on comma
Dim fields = myToken.Split(":")
'Quote literal
Dim quote = """"c
'Use trim to remove quotes
Dim value = fields(2).Trim(quote)
Return value
End Function
End Class
Or as #jmcilhinney said, you can use Module and you don't need to use Shared in the methods inside it (also you can't create an instance of an object from a Module):
Public Module HelperFunctions
Public Function ExtractToken(ByVal myToken As String) As String
'Split fields on comma
Dim fields = myToken.Split(":")
'Quote literal
Dim quote = """"c
'Use trim to remove quotes
Dim value = fields(2).Trim(quote)
Return value
End Function
End Module

RS.exe subscribe report with parameters

I am trying to create dynamic report subscriptions through rs.exe. How ever I cannot get the parameters to work. The enddate value is data/time, so I think that might be causing it, but I do not know what to do about it. I have tried casting, but the error msg. stays the same.
rs.exe call:
C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn>rs.exe -i C:\Users\me\Desktop\rss_gen\subs.rss -s "localhost/ReportserverT"
subs.rss file:
Public Sub Main()
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim desc As String = "Report description"
Dim eventType As String = "TimedSubscription"
Dim scheduleXml As String = "<ScheduleDefinition><StartDateTime>2017-12-08T15:00:00</StartDateTime><WeeklyRecurrence><WeeksInterval>1</WeeksInterval><DaysOfWeek><Thursday>True</Thursday></DaysOfWeek></WeeklyRecurrence></ScheduleDefinition>"
Dim parameters() As ParameterValue
' If you need setup parameters
Dim parameter As ParameterValue
parameter.Name = "enddate"
parameter.Value = "2017-12-30 10:03:01.250" 'this is date/time
parameters(0) = parameter
Dim matchData As String = scheduleXml
Dim returnValue As String
Dim reports() As String = { _
"/My Folder/report"}
For Each report As String In reports
returnValue = rs.CreateSubscription(report, parameters)
Console.WriteLine(returnValue)
Next
End Sub 'Main`enter code here`
Error msg:
C:\Users\mee\AppData\Local\Temp\11\dhexge0m.1.vb(43) : error BC30455:
Argument n ot specified for parameter 'Parameters' of 'Public Function
CreateSubscription(R eport As String, ExtensionSettings As
Microsoft.SqlServer.ReportingServices2005. ExtensionSettings,
Description As String, EventType As String, MatchData As Stri ng,
Parameters() As
Microsoft.SqlServer.ReportingServices2005.ParameterValue) As String'.
Let me teach you a trick to program in .Net and in general. It sounds simple, all you need to do is pass functions what they expect. Let me give you a simple example.
With this code I've got a similar error to you:
CS7036 There is no argument given that corresponds to the required formal parameter 'fileName' of 'FileInfo.FileInfo(string)'
The squiggle red line tells you where the problem is. If I type the opening bracket it will give me a tooltip with what it expects:
Ok it needs a string, so I declare a string and give it to the function as it expects:
So the problem you have is because you are not giving the CreateSubscription function the parameters it expects.
Argument not specified for parameter 'Parameters' of 'Public Function CreateSubscription
To fix it provide all the mandatory parameters to the ReportingService2005.CreateSubscription Method:
public static void Main()
{
ReportingService2005 rs = new ReportingService2005();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
string report = "/SampleReports/Employee Sales Summary";
string desc = "Send email to anyone#microsoft.com";
string eventType = "TimedSubscription";
string scheduleXml = #"<ScheduleDefinition><StartDateTime>2003-02-24T09:00:00-08:00</StartDateTime><WeeklyRecurrence><WeeksInterval>1</WeeksInterval><DaysOfWeek><Monday>True</Monday></DaysOfWeek></WeeklyRecurrence></ScheduleDefinition>";
ParameterValue[] extensionParams = new ParameterValue[8];
extensionParams[0] = new ParameterValue();
extensionParams[0].Name = "TO";
extensionParams[0].Value = "dank#adventure-works.com";
extensionParams[1] = new ParameterValue();
extensionParams[1].Name = "ReplyTo";
extensionParams[1].Value = "reporting#adventure-works.com";
ParameterValue parameter = new ParameterValue();
parameter.Name = "EmpID";
parameter.Value = "38";
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = parameter;
string matchData = scheduleXml;
ExtensionSettings extSettings = new ExtensionSettings();
extSettings.ParameterValues = extensionParams;
extSettings.Extension = "Report Server Email";
try
{
rs.CreateSubscription(report, extSettings, desc, eventType, matchData, parameters);
}
catch (SoapException e)
{
Console.WriteLine(e.Detail.InnerXml.ToString());
}
}
As part of the 2005 report service for ms SQL, none of the parameters passed to CreateSubscription are optional. Please refer to the link and update the way you are calling the function. The error is clear, you are missing the parameters which is the last one. Look at the bottom of the page for an example.
https://technet.microsoft.com/en-us/library/microsoft.wssux.reportingserviceswebservice.rsmanagementservice2005.reportingservice2005.createsubscription(v=sql.90).aspx

Secret message encrypt/decrypt ÅÄÖ

I need to add this encryptdecrypt code ÄÖÅ characters, but i don't know how?
Here's my code:
Public Function EncryptDecryptString(ByVal inputString As String, Optional ByVal decrypt As Boolean = False) As String
Dim sourceChars As String = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim resultChars As String = "36N8lkXruq94jMZInPpshR xHc2mTQb7eYai5vGWDzFdoC0wKSBt1EOgVALJfUy"
Dim result As String
If decrypt Then
result = New String(inputString.Select(Function(c) sourceChars(resultChars.IndexOf(c))).ToArray())
Else
result = New String(inputString.Select(Function(c) resultChars(sourceChars.IndexOf(c))).ToArray())
End If
Return result
End Function
You current code will work (as well as it does for English characters) if you simply add the Swedish characters to both sourceChars and resultChars like this.
Dim sourceChars As String = " ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÅabcdefghijklmnopqrstuvwxyz0123456789äöå"
Dim resultChars As String = "äöå36N8lkXruq94jMZInPpshR xHc2mTQb7eYai5ÄÖÅvGWDzFdoC0wKSBt1EOgVALJfUy"
However, your code will fail if the input string contains any character that you are not expecting (for example a tab character or newline). Here is a version of the function that doesn't throw an exception on an unexpected character, but simply uses it without encrypting that character (for serious encryption, it would be better to get an exception).
Public Function EncryptDecryptString(ByVal inputString As String, Optional ByVal decrypt As Boolean = False) As String
Dim sourceChars As String = " ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÅabcdefghijklmnopqrstuvwxyz0123456789äöå"
Dim resultChars As String = "äöå36N8lkXruq94jMZInPpshR xHc2mTQb7eYai5ÄÖÅvGWDzFdoC0wKSBt1EOgVALJfUy"
Dim result() As Char = inputString
Dim inChars As String = If(decrypt, resultChars, sourceChars)
Dim outChars As String = If(decrypt, sourceChars, resultChars)
For i As Integer = 0 To inputString.Length - 1
Dim pos As Integer = inChars.IndexOf(inputString(i))
If pos >= 0 Then result(i) = outChars(pos)
Next
Return result
End Function

Cannot Declare String In Module VB6

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