how to see a change in a value in looping? - vb.net

how to see a change in a value in the following looping
Dim one, two, three, four, five as integer;
two = 0;
three = 0;
four = 0;
five = 0;
for one = 0 to 10
if ((one Mod 4) = 0) Then
two = two + (one+three)-five
End if
if ((one Mod 3) = 0) Then
three = three + (one+two)-four
End if
if ((one Mod 2) = 0) Then
four = four + (one+two)-three
End if
if ((one Mod 1) = 0) Then
five = one+ two + three
End if
Next
two = how much has it changed?
How much is the value of one when the two value changes?

This seems like a homework assignment where the purpose is NOT to see if you can produce the right answer. Rather, the purpose of this assignment is to teach you to use the Visual Studio debugger.
Therefore, the correct answer here is to create a new VB.Net Console project in Visual Studio. Then paste this code into the Main method for the new project, set a breakpoint (F9) on the first line and hit F5 to start the debugger.
When you reach the breakpoint, you can use the Locals window at the bottom of Visual Studio to check the value of each local variable, and use the F10 key to continue running just one line of code at a time.
In this way, you will be able to see when a variable changes, as well as the value of other variables at that time, and in this way answer the questions.

Related

Attaching specific files based on the user's selection in a userform

For the next part of this project that I've been working on to speed up follow up emails to clients for the office, I'm looking to grab a specific attachment from a specified filepath based on the items that the user selected on the userform. These emails will always be sending the exact same files so the less time the user has to spend manually attaching files, the better it will be. My first assumption right off the bat was that I'd need a loop to do this, so I began to do my groundwork, but now I'm generally stuck.
The first loop grabs what the user selected from the userform:
For i = 0 To List1.ListCount - 1
If List1.Selected(i) Then
Counter = Counter + 1
msg = msg & "<font style = 'background: yellow'>" & List1.List(i) & "<br />"
Else: If Counter = 0 Then End
End If
Next
And the second loop attaches the files based on the selections above:
For i = 0 To List1.ListCount - 1
If List1.Selected(i) Then
Counter = Counter + 1
.Attachments.Add List1.List(i)
Else: If Counter = 0 Then End
End If
Next
The attachments process just fine.However, the program ends up displaying the highlighted body of the message as the filepath I tried to associate with the list item:
' test files
List1.List(0) = "C:\Users\jmarkman\Dropbox\Python Practice\ex1.py"
List1.List(1) = "C:\Users\jmarkman\Dropbox\Python Practice\ex2.py"
List1.List(2) = "C:\Users\jmarkman\Dropbox\Python Practice\ex3.py"
List1.List(3) = "C:\Users\jmarkman\Dropbox\Python Practice\ex4.py"
List1.List(4) = "C:\Users\jmarkman\Dropbox\Python Practice\ex5.py"
List1.List(5) = "C:\Users\jmarkman\Dropbox\Python Practice\ex6.py"
So my question is, how do I associate these file paths with corresponding items in the listbox within the userform? I'm pretty sure that although it worked, the process changed the list items since I assigned them a different value.
I'm not sure how complex or simple this might end up being, so your time and patience are well appreciated.
People have said that one can learn best just by doing and making mistakes, but let me tell you that not having someone you can at least talk to about where to start making mistakes is incredibly frustrating. I hope anyone else who, like me, was on the cusp of solving this problem is able to look here and have their own "a-ha!" moment.
When I first asked this question, I was on the right path with choosing to put all of my filepath locations within an array and I was further along the right path by using a loop to go through it. I declared the myAttach array with a range as I did at first, but unlike whatever example I saw during my google research, I kept my second attachment loop the same but simply changed out List1.List(i) for myAttach(i). That made the script's wheels turn and performed all the functions I needed it to.
The long and short of it was that I made an array that matched the quantity and order of the items in the userform and re-used the loop I made for picking the subjectivities, I was able to associate the choices in the userform to those in the array by having the second loop go through the array. Each listing in the array had a filepath associated with it.
' example
myAttach(0) = "[filepath]"
myAttach(1) = "[filepath]"
myAttach(2) = "[filepath]"
myAttach(3) = "[filepath]"
' ... and so on ...
It helped to visualize the array and the list items as two side-by-side columns; the first item in the list is parallel to the first item in the array, and can therefore be recognized by the second loop. If a mental image isn't forthcoming, try inputting some data into two or more Excel columns to witness the relationship or review Matricies.
A caveat of this line-up approach, I found out shortly after while continuing research to figure out exactly what I did right this time would be if I had to have the items in the list in a specific order (i.e., alphabetical), but fortunately the list items are phrases and complete sentences and don't require sorting.
Happy learning and programming!

generating random numbers in visual basics

I am using a random number generator in my program, however it keeps returning the same value (0.71) every time i run the program.
code:
number = FormatNumber(Rnd(1), 2)
rdmlabelTxt.Text = number.ToString
is there a way to produce a different random number when starting the program?
thanks.
According to Microsoft "the same number sequence is generated" when you don't give a parameter. The article also suggests to "Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer."
I think this will solve your issue - let us know.
You are required to write a for loop to be able to generate different numbers
For i = 1 to 100
number = FormatNumber(Rnd(1), 2)
Cells(i, "A").Value = number
next i
You just have to use Randomize() call before your codes.
Randomize()
Dim number As Double = 0
number = FormatNumber(Rnd(1), 2)
rdmlabelTxt.Text = number.ToString

VBA Excel Break Points and Stop do not work

Any idea why inserting break points and stop no longer stops my vba code from running?
The code runs ok all the way to the end (I tested it) but ignores break points and Stop.
Also step into just makes the code run in it's entirety, ignoring break points and stops.
When I close the workbook where the issue seems to originate from the same issue occurs in other macro workbooks.
if I completely close excel and re-open it with a normally working macro workbook the issue doesn't occur until I re-open the problem work book.
I added breakpoints on:
TotP1 = 0
of the following code:
Option Explicit
Private Country As String
Private Measure As String
Private P1 As String
Private P2 As String
Private TotP1 As Double
Private TotP2 As Double
Sub VennDisplayIt()
Dim SI() As String
Dim SICount As Integer
Dim x As Integer
Dim OSh As Worksheet
Dim BrandListBox As Object
Dim VennGroup As Shape
TotP1 = 0
TotP2 = 0
Set OSh = ThisWorkbook.Sheets("Venn")
Set BrandListBox = OSh.OLEObjects("BrandListBox").Object
ReDim SI(2, 0)
For x = 0 To BrandListBox.ListCount - 1
If BrandListBox.Selected(x) = True Then
'If UBound(SI) < 4 Then
ReDim Preserve SI(2, UBound(SI, 2) + 1)
SI(1, UBound(SI, 2)) = BrandListBox.List(x)
SI(2, UBound(SI, 2)) = x + 1
'End If
End If
Next x
If UBound(SI, 2) < 2 Then
BrandListBox.Selected(BrandListBox.ListIndex) = True
Exit Sub
ElseIf UBound(SI, 2) > 4 Then
BrandListBox.Selected(BrandListBox.ListIndex) = False
Exit Sub
End If
For x = 1 To UBound(SI, 2)
OSh.Range("o8").Offset(x, 0).Value = SI(1, x)
OSh.Range("o8").Offset(x + 5, 0).Value = SI(1, x)
Next x
For x = UBound(SI, 2) + 1 To 4
OSh.Range("o8").Offset(x, 0).Value = ""
OSh.Range("o8").Offset(x + 5, 0).Value = ""
Next x
SICount = UBound(SI, 2)
For x = 1 To OSh.Shapes.Count
If Right(OSh.Shapes(x).Name, 5) = "Group" Then
If LCase(OSh.Shapes(x).Name) = SICount & "waygroup" Then
Set VennGroup = OSh.Shapes(x)
OSh.Shapes(x).Visible = True
Else
OSh.Shapes(x).Visible = False
End If
End If
Next x
For x = 1 To SICount
VennGroup.GroupItems.Item(SICount & "WayBrand" & x).DrawingObject.Text = SI(1, x)
Next x
Country = ThisWorkbook.Sheets("Venn").Range("D4").Value
Measure = ThisWorkbook.Sheets("Venn").Range("E32").Value
P2 = ThisWorkbook.Sheets("Venn").Range("E31").Value
P1 = ThisWorkbook.Sheets("Selections").Range("B5").Value
End Sub
I've never heard of Stop not working, but I've heard about and experienced the breakpoint thing many times. When you compile VBA, it creates a p-code, which is used by the interpreter. You have the VBA syntax layer that you can see and the p-code layer that you can't see. When breakpoints stop working, it's because the p-code was corrupted. I don't know how or why it happened, but it did.
The fix is to export, remove, and reimport all of your modules. Exporting them creates a .bas file (plain text, really). When you re-import, the p-code is regenerated from scratch. If you have more than a couple of modules, get CodeCleaner (free add-in) and it will export and reimport automatically.
If one of the settings is unchecked then breakpoints will not work. "File/options/Current database/Application options/use access special keys" should be checked
Just to 'second' Tibo's comment: I had a problem where I had a form with about 5 different subroutines. One of them (attached to a button event) would not stop when I set a breakpoint. in 10 years of VBA writing, I've never seen that happen. Interestingly, breakpoints worked on all of the other subroutines in that form. After much head-scratching and searching, I came upon this post and Tibo's comment. I added a "Stop" command to the affected subroutine, ran the procedure (it stopped as it should have) and then breakpoints began working again! Hope this helps someone in the future.
If the breakpoints are in your code, then the code should stop running as soon as it hits that line. Possible causes of your problem:
a) The code never gets to the Breakpoint.
Seems highly unlikely seeing as you're breaking on the first line of your code. Maybe step through the sub (F8) just to check it's running as it should.
b) Your breakpoints have been wiped. Any line with a breakpoint should display as highlighted in red on your IDE. Your breakpoints can easily be wiped through, e.g. closing and opening the workbook (a screenshot would be really useful).
c) your workbook is broken in some way. It would be unlikely to break something as fundamental as stopping at breakpoints and still function normally. Are you sure your code is actually running?
Just sharing a funny thing which happened to me in case it helps someone. The mistake I did was that I simply took someone's method code meant for workbook open event and pasted it on Sheet1 excel object code area. So there was no possibility of Workbook_Open method getting fired ever.
Private Sub Workbook_Open()
Stop
On Error Resume Next
Call ActiveSheet.Worksheet_Activate
On Error GoTo 0
End Sub
What I was supposed to do is paste this method after double clicking ThisWorkbook node under Microsoft Excel Objects in Project pane as shown below:
Note: Side effect of copy-pasting others code can be freaky at times.
a) Double check that your breakpoints got disabled or not.
b) Double check that you added a conditional breakpoint or not
c) If you run your macro using C# code (using, the _Run2 command), breakpoints and stop doesn't work sometimes.
I have the problems as described above:
Stop and Breakpoints not working
Single step F8 worked, but code was not highlighted in yellow
Closing VBA editor did not help
My remedy: close VBA editor again, save Excel-file, open editor, back to normal
I've never faced this problem for years. Today for the first time I started using watch expressions with stopping when true.
This happens to me once in a while and the following solves the problem for me every time:
Create a Sub with only the command Stop in it. Run it. Then try your routine, the breakpoints and Stop commands should now work correctly.
Make sure that you do not have a named Range that matches the name of the Function or Subroutine you are calling. This will look like the Function or Subroutine is failing, but it is actually failing before the routine is ever called with an 'invalid cell reference'.
I had this problem as well. My solution was put an error in the code and run it. After I cleared the error the breakpoints started working again. That was weird.
I been writing code in VBA for many years but today I came across this problem for the first time. None of the solutions I found on the web worked but here's something simply you can use instead of Stop:
ErrCatch = 1 / 0
Still doesn't solve the breakpoints not working though...
I went int my vba code, added an enter (new blank line), then ran it again.
Voila! It ran the code and stopped at the breakpoint!
Not just me then! On a few occasions the yellow hi-lite stops a few lines beyond the breakpoint! I guess the code is running so fast it can't stop in time. :) As suggested above, I find adding "stops" here and there and also exporting & re-importing helps too.

Visual basic continuing variables

I am making a calculator app as my first self assigned project using Visual basic, and I want it to continue accepting numbers to calculate possibly up to a hundred different numbers, and I don't want to have to make a variable for all of them(not to even mention if that would work). The way I see it is that every different number entered into the calculator between operators would be stored as a different variable. Is this possible? maybe a work around? maybe even a better way to do it! any help is appreciated! thanks!
If you use a While loop you can do this fine.
All you need to do is set variables for Multiply, Subtract, Divide, and Add which should be as Booleans and declare FinalAnswer and Input as Dec.
Do something like:
While VariableToShowIfACalculateButtonIsPressedOrNot = False
If Multiply = True Then
FinalAnswer = FinalAnswer * Input
ElseIf Divide = True Then
FinalAnswer = FinalAnswer / Input
ElseIf Add = True Then
FinalAnswer = FinalAnswer + Input
ElseIf Subtract = True Then
FinalAnswer = FinalAnswer - Input
End If
Loop
For whenever you input another number. Have this assigned to a separate button called 'AddNumber' or something.
As soon as you want to output the total of all of these then you can have another button called 'Calculate' or something which could have something like:
FinalAnswer = TextBoxAnswer.txt
You could also have this set at the bottom of the While loop which would give you a running total of all the numbers you have input so far.
Hope this makes sense!

Modifying text in the console using Visual Basic

I was wondering if there is a more efficient way of modifying the text in the console. For example: if I am keeping track of the number of events that have occurred, I'll print
0 events have occurred
and as events occur I want to increment that 0.
Currently I am doing that in a very ugly way:
Keep track of everything printed to the console using a String or Stringbuilder and if I need to make any changes, change the string, clear the console, print the string to the console. Aside from probably not being very efficient, it displays in an ugly way resulting in the console's "blinking" when too many changes are made in a short period of time.
Thanks in advance.
The trick is to use the carriage return code. This basically returns the cursor to the beginning of the same line. This is different from the carriage return + line feed (vbCrLf), which puts the cursor at the beginning of the next line.
There are slightly different ways to do this in VB vs. C#.
VB: Use the vbCr code.
C#: Use the \r code.
Here's some sample code:
VB:
For i = 1 To 100
Console.Write("Processing...{0}% complete " & vbCr, i)
System.Threading.Thread.Sleep(100)
Next
C#:
for (int i = 1; i <= 100; i++)
{
Console.Write("Processing... {0}% complete\r", i);
System.Threading.Thread.Sleep(100);
}