break function not stopping loop - python-3.x

I'm trying to create a code for light consumption and I want that if the day introduced is on the weekend , to show "Estás en el tramo valle, aprovecha para hacer lavadoras!" and break the loop but if the day is on the weekday, to check the hour and then, print the different messages depending on the hour.
If the day is on the weekday, it works fine, but if the day is on the weekend, I get the 2 messages, the one saying "Estás en el tramo valle..." and the other checking the hour.
I would like the "for h in hora" part to be indented on the upper part but when I do so, I get the message duplicated 6 times (one per if function)
Could you help me? Is there any function to do this?

It would be easier to answer if you had your code pasted, but I can still describe what you need to do.
Create a variable such as weekend and set it to false. Before each break of the first for loop, set weekend to True. Before the second for loop, put a for loop checking if weekend is false
weekend = False
for x in dia:
if dia == '...':
print('...')
weekend = True
break
if dia == '...':
print('...')
weekend = True
break
if not weekend:
{second for loop}

Related

Import Time Data from MATLAB to Excel

I have a machine that has a starting time and end time as shown below:
I want to read this values in MATLAB and save it to format HH:MM:SS, I'm using this command
filename='Name.csv';
W=xlsread(filename, 'B5:B5');
t = datetime(W,'ConvertFrom','excel');
I want to get a final array that starts with the start time and add 1 second until it reach the last time like this
time=[3:45:13,3:45:14,3:45:15,3:45:16,........,11:25:06]
Any ideas ?
Thanks in advance
So you've gotten this far:
W = xlsread(filename, 'B5:B5');
t = datetime(W,'ConvertFrom','excel');
P = xlsread(filename, 'B6:B6');
t1 = datetime(P,'ConvertFrom','excel');
At that point you have your start time in t and your end time in t1.
Similar to how you can construct ranges of numbers using the notation a:b, you can construct ranges of times using datetimes and the : operator. Use start_time:step_size:end_time to set the step/interval size.
time = t:seconds(1):t1
Then you can use datestr() on the results to convert it to whatever display format you want.

Can For loops be dynamic in that the limits change as the code is run?

I'm creating a forecasting model for a fleet of equipment using Excel wholly written with VBA.
While forecasting the utilisation of equipment, some equipment will reach its replacement threshold and a new piece of equipment takes over from there. This will require a new row added to the table for the new equipment.
I would have thought that a For loop would be dynamic, so using a variable for the upper limit would be re-evaluated on every loop, but this seems not to be the case.
I set up a simple scenario to test as per the code below, starting with 2 listrows in the table.
Sub Test1()
Set Table1 = Sheet1.ListObjects("Table1")
x = Table1.ListRows.Count
For i = 1 To x
Set NewRow = Table1.ListRows.Add
x = Table1.ListRows.Count
NewRow.Range(1, 1) = x
Next i
End Sub
I assumed it would run infinitely but it will only run as per the initial case provided.
Is using a different type of loop (Do While or Do Until) the ONLY way to achieve a genuinely dynamic outcome?
To sum things in the comments to your question up:
Modifying the target of a for-loop might be prohibited in Viual Basic. There are other languages out there that in principle allow for this kind of operation, however, it's not a good programming style.
The reason is, that a for-loop is a loop counting over a fixed interval (that should not change during the loop's execution).
Instead of using a for-loop here, one may consider using a while-loop:
i = 1
While i <= x
Set NewRow = Table1.ListRows.Add
x = Table1.ListRows.Count
NewRow.Range(1, 1) = x
i = i+1
Wend
Caution:
This loop will run forever (or rather: until you reach a maximum of resources, in which case it will crash). The reason is, that you move the upper bound for the iteration 1 unit further away while approaching it by 1 unit.
The best way to approach what you actually want to achieve is using a buffer list:
Identify the items you want to create a new row for
Insert that row into a second list
Iterate over the second list and append the items to the original list
This way, you avoid testing the newly inserted items (which most likely won't be outdated by now).

Hide and unhide series in a chart based on their name and i have error 1104

I am trying to hide and unhide series in a chart based on their name using excel vba and I have a error 1004 invalid parameter after the first run of the for cycle.
Sub macroChart3()
'
' macroChart3 Macro test
'
Dim i, n As Integer
For i = 1 To 96 Step 1
If ActiveChart.SeriesCollection(i).Name = "*contracted*" Then
ActiveChart.SeriesCollection(i).IsFiltered = False
Else
ActiveChart.SeriesCollection(i).IsFiltered = True
End If
Next i
End Sub
SeriesCollection.IsFiltered method seemed to toggle this check box:
I couldn't use that. I wanted to record macro and see if any other method is used but the checkbox is gone in 2010:
So it might be not possible to use that anymore. If you are using a different version where this method exists you might have a problem that the series is not listed in in seriesCollection anymore:
Remarks from MSDN
When a user filters out a series, the series IsFiltered property switches to True, and the series is transferred out of its parent SeriesCollection.
See if you can use FullSeriesCollection instead when you change the visibility of series:
ActiveChart.FullSeriesCollection(2).IsFiltered = True
If that doesn't work you might add and remove ranges instead of hiding them.
UPDATE:
Run your macro in step mode (F8) so you have full visibility of the execution steps. Add your evaluated expressions (ones that are used within IFs) to see their result and you will find out if they are incorrect or are evaluated as FALSE and try to figure out why.
And don't forget to up vote the answer if you find it helpful.
thanks for the quick reply, the error is fixed, but still not all the series are processed by the if clauses in the for cycle, for example this statement:
Else
ActiveChart.SeriesCollection(i).IsFiltered = True
End If
Isn't executed and I don't understand why.

Now() is giving an error

I am getting an error in the below code.
Dim CurrentTime As Date
CurrentTime = Format(Now(), "hh:mm AM/PM")
If CurrentTime = ActiveSheet.Range("I1") Then
Call SendEMail
End If
When the time is right, then the macro is debugging and Now is highlighted.
Could anyone solve this problem?
You are not getting an actual error are you? It is just not working as expected.
Matt Cremeens has identified your issue I believe, you have declared CurrentTime as a date data type. A date data type stores a number representing a time/date, however you are asking for it to store string information (AM/PM) too which is can't so it is getting stripped out.
The results is cell one may hold a value like '10:30 AM' but the Format(Now(), "hh:mm AM/PM") code going into the Date variable is resulting in '10:30:00', so the two are never matching as strings. Copy as Matt has suggested and this should work (Dim CurrentTime As String).
Better yet, use the date comparison function DateDiff:-
If DateDiff("s",ActiveSheet.Range("I1"),Time()) > 0 then
SendEmail
End If
This is saying if the time now is greater than the value in I1 (to the second) then run SendEmail.
I don't have the environment to test the solution right now but from what I remember you don't need the brackets in 2007 and also you don't need the format.
Try the following code and see if that fits your need:
If Hour(Now) = ActiveSheet.Range("I1") Then
(...)
End If

VBA stops printing values in excel

I have written a macro to take values from an external simulation tool and prints the results in excel.The simulaion tool will give values only every 30 seconds and will run for days. Hence i have given a delay in VB for 30 seconds in loop. I leave it overnight for running. In the next morning i could see none of the results were updated after certain rows.But the VBA editor header shows the macro is running and the external simulation tool is also running. The last updated row in excel is not constant everytime. Why does VBA stops printing the results in excel? Any help will be much appreciated.
Sample code:
For l = 3 To lastrow1_mul + 2
Module4.Wait 30
nv = send_data.Call
Sheets(SecondSheetName).Range(SecondSheetCol_9 & l) = Hex(nv)
dv = DT.Call
If dv = 44 Then
Sheets(SecondSheetName).Range(SecondSheetCol_10 & l) = "A"
ElseIf dv = 54 Then
Sheets(SecondSheetName).Range(SecondSheetCol_10 & l) = "B"
Else
Sheets(SecondSheetName).Range(SecondSheetCol_10 & l) = "C"
End If
Next l
Module 4:
Function Wait(PauseTime As Single)
Dim StartTime As Single
StartTime = Timer
While Timer < StartTime + PauseTime
DoEvents
Wend
End Function
Send_data and DT are external simulation tool's functions.Variable lastrow1_mul's value is getting updated around 7000 but rows in excel stops printing around 500 itself(not constant always) .
looks OK but look at using Application.OnTime shown below. Also what happens if the simulation hasnt returned data, shoudnt you build in a bigger, maybe 45 second intervals?
Application.OnTime Now + TimeValue("00:00:30"), "RunProcess"
The 'Timer' i used in the code was the culprit. Timer counts the seconds elapsed(in fractions) since midnight. So it will not update when the time becomes 00.00.00. So the wait function i wrote will keep on waiting!
Here is the solution
Function Wait()
Dim StartSecond As Single
Dim EndSecond
StartSecond = Now
EndSecond = DateAdd("s", 30, Now)
While Now < EndSecond
DoEvents
Wend
End Function

Resources