Defined Error in Visual Basic - vba

When i using this const statement,my coding work fine.
Const strFullName As String = "C:\Sample\Haha.txt"
After i change the Search.text (Textbox Name),it keep on come out the error.
Const strFullName As String = "C:\Sample\" & Search.Text & ".txt"
Compile error:
Constant expression required
Then i try create a textbox1.text = Searchbox.Text. The textbox1 shows C:\Sample\Haha.txt
Please Help,Thanks~

Search.Text is not a constant value - it's a run-time property and its value is not known until run-time so it cannot be assigned to a constant. You can just define your strFullName as a variable instead of a constant:
Dim strFullName As String
...
' Set strFullName at run-time
strFullName = "C:\Sample\" & Search.Text & ".txt"
If Search is a textbox, you may also want to check if it has valid input to make sure that you're not trying to form an invalid file name; for example, you can use Len(Search.Text) to determine the length of the text in the textbox.

Related

Generate a SSRS report in default browser from VB.NET

I have a VB.NET solution that stores data to a SQL database. I have written the first of several SSRS reports. Now I want to generate the reports from my VB.NET solution.
I have a subroutine that will generate the report,
Public Shared Sub GenerateReport(ByVal RptName As String, ByVal ParamArray Params() As Object)
Dim strPath As String = sqlSSRS + Replace(RptName, " ", "%20")
Dim _class As cParameters
'strPath += "&rc:Parameters=false&rs:Command=Render"
'strPath += "&rs:Command=Render"
For i As Integer = 0 To UBound(Params)
_class = DirectCast(Params(i), cParameters)
strPath += "&" & _class.ParamName & "=" & _class.Value
Next
System.Diagnostics.Process.Start(strPath)
End Sub
If I generate a path with no parameters the report will open in the default browser. So this works...
http://sqlServerName:80/Reports/report/ToolCrib/Toolbox%20by%20Installer
But neither this ...
http://sqlServerName:80/Reports/report/ToolCrib/Toolbox%20by%20Installer&#UserID=7&#ProjectID=20026&#ToolboxID=10&#ToolStatus=2
or this
http://sqlServerName:80/Reports/report/ToolCrib/Toolbox%20by%20Installer&UserID=7&ProjectID=20026&ToolboxID=10&ToolStatus=2
does.
I obviously have an issue passing parameters. In one case I don't need them but in other cases I want to provide them, which is why I wrote the GenerateReport routine with the optional Parameter array. Here is the error message I get which I know from past experience is sort of a catch all when MS doesn't "know" how else to classify an SSRS error.
The path of the item '/ToolCrib/Toolbox by Installer&UserID=7&ProjectID=20026&ToolboxID=10&ToolStatus=2' is not valid. The full path must be less than 260 characters long; other restrictions apply. If the report server is in native mode, the path must start with slash. (rsInvalidItemPath)
Any help will be greatly appreciated.
You path needs to use reportserver? instead of Reports/report when using parameters.
Try
http://sqlServerName:80/reportserver?/ToolCrib/Toolbox%20by%20Installer&UserID=7&ProjectID=20026&ToolboxID=10&ToolStatus=2
You could add a REPLACE:
strPath = Replace(strPath, "/Reports/report/", "/reportserver?/")
For more reading, you can check out
MS Docs url-access-parameter-reference

Parse enum values by name in VBA

I want to write some VBA code that should parse MSForms-constant names (given as a string, like "fmTextAlignLeft") into their actual value. Since there is no native way to do so I was considering to put the name of the constant into a powershell code that will then be executed and return the result.
Private Sub ParseEnumByName(EnumConst As String)
Dim WScript As New WshShell
Dim PSCode As String
Dim Result
PSCode = "(some code)" & EnumConst & "(more code with exit $Value statement)"
Result = WScript.Run("Powershell -command """ & PSCode & """", 0, True)
ParseEnumByName = Result
End Sub
This should be feasible by iterating through all enums in the MSForms library and get the values out of them with something like
[System.Enum]::GetNames( [System.Windows.Forms.FormBorderStyle] ) or maybe something like explained here: How to convert a string to a enum?
The problem is that the System.Windows.Forms library contains totally different enums and typenames than the MSForms library available in VBA.
I tried to Add-Type -Path "C:\Windows\SysWOW64\FM20.DLL" where the MSForms library is stored but it returns an error saying the file or assembly or some related file could not be found.
How may I get a reference to MSForms in Powershell?
Edit: I have actually found a demi-native way in VBA (Excel VBA only) to solve this issue without passing values to external script hosts. Please see below.
Here's the function I figured out. So far it seems to work with all pre-defined enums and constants and also self defined enums in Excel. The function must be placed in a module!
Static Function ParseValue(StringValue) As Variant
Dim ParseValueBuffer As Variant
If IsEmpty(ParseValueBuffer) Then
ParseValueBuffer = 1
Application.Run ("'ParseValue " & StringValue & "'")
ParseValue = ParseValueBuffer
ParseValueBuffer = Empty
Else
ParseValueBuffer = StringValue
End If
End Function
Sub TestMe()
MsgBox "First line" & ParseValue("vbcrlf") & "Second line"
MsgBox ParseValue("fmTextAlignCenter") 'Should return "2" (if MSForms is referenced)
MsgBox ParseValue("rgbblue") 'Should return 16711680
End Sub

Conversion From String To Integer Not Valid Error But No Numbers Or Integer Types Specified

I'm new to VB and I'm hoping someone can help with the first major problem I've encountered.
I've created a form, which:
Allows me to specify a SearchString in a text box
To specify a FolderPath using FolderBrowserDialog in a text box
Pass the values in the text boxes as variables
Return all files in the FolderPath, containing the SearchString, with wildcards, to a ListBox when a button is clicked.
The code behind the button is as follows:
Private Sub ListButton_Click(sender As Object, e As EventArgs) Handles ListButton.Click
Dim fls
Dim FolderPath As String
Dim SearchString As String
FolderPath = FolderPathBox.Text
SearchString = SearchStringBox.Text
fls = My.Computer.FileSystem.GetFiles(FolderPath,"*" & SearchString & "*")
For Each f As String In fls
MatchingFilesBox.Items.Add(f)
Next
End Sub
However, after populating the SearchString and FolderPath text boxes with the following values respectively:
(1)
C:\Backup\Files
and clicking the button, the following error is returned:
Additional information: Conversion from string "* (1)*" to type 'Integer' is not valid.
The same error is displayed even if I do not specify a number e.g. "an" and I've not specifically configured any text boxes or classes or variables as data type integer.
I've simplified the code by removing the variables and wildcards from the equation and hard coding the path and a file name:
'fls = My.Computer.FileSystem.GetFiles(FolderPath,"*" & SearchString & "*")
fls = My.Computer.FileSystem.GetFiles("C:\Backup\Files", "abandoning.docx")
But the same error on converting to data type integer is displayed:
Additional information: Conversion from string "abandoning.docx" to type 'Integer' is not valid.
I'm flummoxed as to why or how an integer is being passed or retrieved in the file path. I've searched for answers to the error, but the articles I've read relate to number values, while mine doesn't; or to empty textboxes, which I believe I've eliminated; or use Replace, which I'm not.
Can anyone offer any guidance on overcoming this issue, so I can return all files in a folder containing a specific string in the filename?
You are passing in the incorrect number of parameters. The second parameter is supposed to be an enumeration of which is always a number. The last parameter is your wild card which can be a string. Try this:
fls = My.Computer.FileSystem.GetFiles("C:\Backup\Files", SearchOption.SearchTopLevelOnly "*.docx")
Look here for the reference as to what you are to pass in to the GetFiles() function:
https://msdn.microsoft.com/en-us/library/t71ykwhb(v=vs.90).aspx

VBA Compile Error on Function Call

so I'm trying to run this SQL script within a function I call and it's giving me a "Compile Error: Object Required" when I try to run it!
Code calling the function
Private Sub cmdLogin_Click()
Call Load_Username(Username)
End Sub
Function being called
Private Sub Load_Username(Text As String)
Dim SQL As String
Set SQL = "UPDATE tbleUsername " & _
"SET Username = '" & Text & "' " & _
"WHERE ID = 1"
DoCmd.RunSQL SQL
End Sub
Dim SQL As String
Set SQL = "string literal"
You can't use Set to assign a string literal. Use Set to assign object references. That assignment is illegal, because an object is required. Hence, Object required.
Two possible fixes:
Remove the Set keyword and use the wonderful implicit value assignment syntax.
Replace the Set keyword with the obsolete Let keyword for a long-deprecated explicit value assignment syntax. Only suggesting because I'm seeing you use the long-deprecated Call keyword too.
I think that you should define variable Username before call function LoadUsername(UserName)

Concatenating a complex string in VB. NET

I am using START-PROCESS to call MSTEST with multiple arguments that define the container and test settings, however I think it's choking on the way I'm concatenating this. Should I use some other method of constructing this string before putting it into START-PROCESS?
Dim rwSettings As String = "\\PerfvsCtlr2\LoadtestSettings\PerfVSCtlr2forRemote.testsettings"
Dim rwContainer As String = "\\PerfvsCtlr2\LoadTest\LoadTestDefs\Heifer_Interactive_Peak_Workload.loadtest"
Dim rwResults As String = Workload.txtRwResults.Text
System.Diagnostics.Process.Start(Environment.GetEnvironmentVariable("VS110COMNTOOLS") & "..\Ide\MSTEST.EXE", "/Testsettings:""" & rwSettings & "" & " /Testcontainer:""" & rwContainer & "" & " /Resultsfile:""" & rwResults & "")
The problem is unknown currently, because process.start opens and closes the window far too quickly for me to catch any sort of error message. So my question is two-fold:
Does the above concatenation look correct? Is there a way I can get more information on either the final execution string Process.Start is putting together or the error message it's returning?
You can use Path.Combine to build paths and String.Format to build the arguments for Process.Start:
Dim rwSettings As String = "\\PerfvsCtlr2\LoadtestSettings\PerfVSCtlr2forRemote.testsettings"
Dim rwContainer As String = "\\PerfvsCtlr2\LoadTest\LoadTestDefs\Heifer_Interactive_Peak_Workload.loadtest"
Dim rwResults As String = "Workload.txtRwResults.Text"
Dim fileName = System.IO.Path.Combine(Environment.GetEnvironmentVariable("VS110COMNTOOLS"), "Ide\MSTEST.EXE")
Dim args = String.Format("/Testsettings:{0} /Testcontainer:{1} /Resultsfile:{2}", rwSettings, rwContainer, rwResults)
System.Diagnostics.Process.Start(fileName, args)
However, i must admit thar i'm not sure if this yields the desired result. It might give you an idea anyway.
I suspect that your problem is that you are not closing your quotation marks, for instance:
" /Testcontainer:""" & rwContainer & ""
Should be:
" /Testcontainer:""" & rwContainer & """"
Notice that the double-quotation mark at the end needs to be a quadruple quotation mark. Simply saying "" means an empty string.
Should you use something else? Probably. It would be more readable and efficient if you used StringBuilder or String.Format, but even so, you'll still have to fix the closing quotes issue.