VB Code explanation? [closed] - vb.net

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
Hey can someone explain this VB (Visual basic) code in a way thats simple for everyone to understand even minimal to no coding experience but still explains each section, also what dim and open do. Thanks!
Dim studentname As String
Dim intMsg As String
Private Sub Command1_Click()
‘To read the file
Text1.Text = ""
Dim variable1 As String
On Error GoTo file_error
Open "D:\Liew Folder\sample.txt" For Input As #1
Do
Input #1, variable1
Text1.Text = Text1.Text & variable1 & vbCrLf
Loop While Not EOF(1) Close #1

Declare a student name variable that we will call studentname as a string. Think of variables as you would do x and y in an algebraic equation. They are simply names for things of a particular type. In a maths equation x and y are numbers. A string is a basically a sequence of characters, such as words, numbers, or any other arbitrary data. "Moo-Juice" is a string, for example - delimited by the " characters.
Declare a message called intMsg as a string.
Subroutine "Command1_Click", called when the button (presumably) Command1 is clicked by the user. Subroutines are functions and are where you either put common code that you wish to re-use, or in the case of languages such as this, to respond to events that have occurred. Events in GUI applications come in various different flavours, this one is called when the user clicks a button. Others include MouseMove, KeyUp, KeyDown. Responding to these events allows your code to do stuff.
Set the Text1 control's Text property to an empty string (clear it). Controls on a form (both the text box and the button are examples of controls), have properties. The Text property is where a Textbox control stores what you can see in the textbox. Controls generally have a whole bunch of properties. Left denotes where it is on the form with regards to the horizontal position. Font specifies want font to use, etc, etc. There are many different GUI systems, and beyond VB6 and in the .NET environment there are Windows Forms, and WPF (Windows Presentation Foundation). In other languages there are as many GUI systems as you can care to think of.
Declare variable1 as a string.
Within this subroutine (Command1_Click), should an error occur go to the file_error label that appears not to be in your code snippet so we can assume it is farther down, beyond the loop. GoTo does exactly what it says on the tin - it jumps to the label specified and execution continues there. On Error tells visual basic what to do if an error occurs, and in this case it is saying "Go there if something goes awry".
Open the file specified, in read mode, assigning it file handle #1 for future reference. File handlers, like variables, are a way of identifying a file we want to do something with. Without file handlers (in VB6) if I open multiple files at the same time, how does the system know which one I want to write to? By saying "Open this file, and I'll refer to it as #1", we can tell the system which file we want to play with at any particular point in time.
Begin a loop. There are many loop constructs, and the verbosity of VB6 (and BASIC in general) allows you to see what kind of loop you're doing. This is a Do loop. It will execute at least once, with the condition at the end being checked each iteration. Should that check return true, the loop stops. Other loop types include For (for fine-grained control over steps, and how many iteration. Other languages allow more expressive boolean logic to determine the exact lifetime of a for-loop), and While which is similar to do, but the check is performed at the top, so it may run zero times if the condition fails immediately.
Read in a line from file handle #1 in to our string variable variable1. Remember we've told it which file handle to use and so the system knows where to read the data from.
Append this to the text box we emptied earlier, with a carriage-return & line-feed. Given that we are reading line-by-line, we're preserving the line-endings when putting the text in to the text box. Appending means we're keeping what was there and adding to it.
Keep doing this until we've reached the end of the file. The EOF() function takes a file handle and says whether we've reach the *E*nd *O*f the *F*ile. Remember that the end of our loop terminates if the expression is true. Well, EOF() returns true if we've reached the end of the file. A good time to stop reading it, don't you think? :)
Close the file handle. Enough said! :)
To Summarise
This code snippet reads in a file line-by-line and puts the contents in a textbox, preserving the line-endings.
Issues
intMsg is never used.
Neither is studentname
As mentioned earlier, you're missing the file_error label and the end of the sub-routine (End Sub).

Related

Possible to manipulate text labels in report section headers using VBA? (MS-ACCESS)

Possible stupid question here...
But is it possible in MS-Access to programmatically manipulate text label captions in such a way that that a different caption will appear in the header of each report section?
Ie., The design view shows a text label object in the GroupLevel zero header, with a default caption of "blah"....but upon execution of a Report_Load() sub, the actual text displayed is different for each section in the report? Say, simply "Section 1", "Section 2', "Section 3" and so on?
My suspicion is that this is not possible, but just wondering if anyone has some creative ideas how to make it work.
I realize that there are other/better ways of accomplishing the same thing...but is such a thing possible using VBA and Label objects specifically (at the moment, this is an external constraint and one that I cant change).
EDIT: https://drive.google.com/open?id=1PID58qMyp_rNxv9tsQk38-Co9sDOFgzY
EDIT 2: Original post specifically designated LABELS as the only object for an acceptable solution. Edit to include LABELS and TEXT BOXES...which of course makes the question nearly trivial. Apologies to #peakpeak for my lack of clarity!
You can change the caption with
Me.<name of header>.Caption = "whatever"
Select Properties for the header in design view and find out and/or change the Name property. Me assumes that the VBA code is located under Microsoft Access Class Objects in the form you want to manipulate.
Actually, thank you for your help, but I have found something that appears to function as a decent work-around within the constraints I described above. Strictly speaking, this does not satisfy the terms of the question as originally asked (-1 to me for lack of clarity, and apologies to #peakpeak, who admittedly had essentially zero chance of answering this question as asked), but it this is close enough that it solves my immediate problem:
Change the object intended to contain my dynamic text from a label to a text box (duh!), keep all formatting settings, etc. the same so that the graphical presentation is unchanged.
Set the Control Source of the new text box to a public function, where the argument of the function is the name of a relevant field in the underlying query ("tName" in the linked example), so that the dynamic text box has a control source "=GetText([tName])" and the GetText() function is defined in the appropriate module for the report, and defines the text as desired, e.g.:
GetText(tName as String) as string
SELECT Case tName
Case "Albert"
GetText = "Section 1"
Case "Barry"
GetText = "Section 2"
Case Else
GetText = "Section 3"
'and so on
End Select
`
End Function

Is it possible to copy the contents of the Immediate window in Excel VBA?

Question
I would like to know whether it is possible to copy or extract the contents of the Immediate window in Excel VBA, so I can store it somewhere. I already know you can copy and paste from the window manually, I am interested in whether it is possible to do it with code (preferably in VBA itself).
Explanation
Questions similar to this have been asked a few times on SO (e.g. this and this), no-one has given a definitive answer and I was unable to find one from a quick search. Most of the time, answers respond asking why anyone would want to do that, and give ways to get around it in the circumstances provided in the question (e.g. how to output messages to a file or cell range). Given this, I have thought of a couple of example scenarios where someone might want to do this and cannot (easily) get around it.
Example scenarios
A) I am developing a large workbook including a large set of macros, debugging as I go. This includes using debug.print statements and directly querying in the Immediate window, e.g. ? myVar. At the end of the session, I would like to be able to automatically copy the contents of the immediate window into a log file, so I know what happened during my debug session afterwards. This could, for example, make use of the Workbook_BeforeClose event procedure.
B) I am working with two workbooks that contain VBA projects - one I can't edit, another that I can and am working on. The one I can't edit outputs debug information to the immediate window via debug.print that I would like to store somewhere (but I don't really care where).
Disclaimer
I ask this question purely out of curiosity. I suspect I already know the answer (it's not possible to do this), but I am not sure.
Yes-- but not with control-c .... select what you need and then drag and drop
1-Create a sheet named "debug.print"
2-Hide it:
Sheets("debug.print").Visible = 2 'xlSheetVeryHidden, only can be visible with vba
3-Create this function:
Function debug_print(c As String)
ThisWorkbook.Sheets("debug.print").[a1048576].End(xlUp).Offset(1).Value = c
Debug.Print c
End Function
4-Replace your codes "debug.print" to "debug_print"
5-Example:
Sub blablabla()
debug_print "i am doing whatever"
End Sub
But: Using "?" in the immediate window will not save
There is many ways to export this as file now like CSV, TXT, save in SQL etc...

VBA object properties appear in lower case

Sometimes when developing you find that typical property names show up in lower case.
TempVars.Item("abc")
Might appear like this.
TempVars.item("abc")
Or
tbxMyTextbox.Value
Shows up as
tbxMyTextbox.value
The question is why does this happen and how do you fix it?
I've asked myself this question several times and seen others ask it in SO and elsewhere. In most cases the question comes up when searching for answers on other coding errors. Sometimes the developer (me too) wonders if there's something wrong that they're missing that causes this lower case issue.
A while back I ran across an answer (I'll add the original reference when I run across it again) that made the most sense and actually allowed me to correct this nagging issue.
Apparently it happens when you use a variable in lower case that has a name that's the same as a property.
So
Dim value as string
will result in
myObject.Value
appearing as
myObject.value
Solution?
Because VBE apparently considers this variable across the entire IDE -- apparently without regard to scope; the way to revert to the proper case is to temporarily create the variable in upper case and avoid naming variables with the same name as existing properties in your application.
So the solution for the .value / .Value issue above would be to temporarily include the line
Dim Value as string
in a module within your app. Run the code that includes this line.
Afterwards, remove this temporary line of code.
Then as hoped, .value properties will again appear as .Value and not .value.
Of course, we should avoid those reserved words in the first place, but if at some point that wasn't done the above should fix the issue.
Here are some reserved word links:
Microsoft - Access 2002 & later
Allen Browne's bad word list
Reserved Word search tool (various languages)
Thanks to #ScottCraner for the nudge about avoiding reserved words.
Try something like this:
CallByName(myObject, "value", VbGet)

Embed console in form

TL;DR:
Is there a way to embed a console inside a form, so it becomes a part of it?
Scenario:
I am writing a chat-application with client, server and database using Windows Forms in VB.NET. The server should log all communication it has with clients in a textbox.
The Problem:
So far that would not be a problem - If there wasn't a maxlength for strings! I expect this server to almost never stop (Okay, there is always some point where it does.. but lets ignore that). So if i go for Textbox1.Text &= vbnewline & "Something" it will some day reach this length and run into an exception each time something is about to be logged. I also don't want to just remove the first characters of the string.
My Idea for a solution:
My idea for a work around: Use a console instead of a simple textbox and embed it into the form, so it becomes a part of it. Is there a simple way to do that? By simple I mean that I should have to write thousands of lines of code to achieve that goal.
I am open minded for different ideas and ways to do so as well.
Why not just log your chat to file (you could create a file per day)?
Dim filename = String.Format("C:\Temp\{0:yyyy-MM-dd}-log.txt", DateTime.Now)
My.Computer.FileSystem.WriteAllText(filename, "line of text", True)
Then to display it - use a ListBox and append each new line to the end of the listbox? Each time you append, you could check how many items are in the listbox and remove the first 100 if you are over 1000 as an example.

Creating a self test program with save/import functions (images, description inside)

I'm basically trying to create a program that will allow me to use textboxes to input questions and associated answers to test myself. Mostly, I just want to practice some things I've been learning for vb.net while taking an extra step forward.
Here's a mockup:
Any tips on how to do this? What I'm especially not sure about is how to have the textfile save/import work with adding back into comboboxes and making sure the correct questions and answers are associated with one another. I was thinking also that I could have some sort of check when I import a save file that shows me which questions and answers refer to one another
Update on form design:
Some things I'm trying to practice:
Using arrays
Saving/Opening files (text files in this)- in order to import into program
importing into program
Using the progress bar
Having a way to undo entries
Randomizing sort order in the combo box
Maintaining references between variables (like which answer
corresponds with which question) regardless of sort order or using
the undo function
Some posts in stackoverflow I'm thinking of using as reference:
Compare String with Strings in array
Best way to associate two strings of text in VB.NET
Array to combo box?
Update: Trying to be more specific on my question. Basically, I'm trying to use a list to account for all the inputted questions and answers, however I've only used really basic arrays before, like:
val(1) = "test"
val(2) = "this"
val(3) = "string"
Or the kind where you use a For x to z loop. Based on some stackoverflow posts I've gotten to the point where the code works in that (I think?) the list is updated and the combobox for questions and answers reflect what is on the list. However, I can't connect the two so that I can select things in the comboboxes and check if they are correct.
In terms of saving as a text file. I figured it would be simpler. Basically, have it output sort of like
"question goes here" ; "answer goes here"
"next question goes here" ; "answer goes here"
and so on. Then I can use the semicolon as reference in the code when importing. I've never done it before, but it's generally what I do for Microsoft Access or Excel text imports so I figured it was possible.
Code that I have so far (reddit post link): http://redd.it/2716tw