Datediff in an If statement - if-statement

For some reason I can't figure out why the code below doesn't seem to work it will only display one or the other and wont switch. I am also wanting it do make the text box blank if neither of them are true. Any help would be so great.
Private Sub txtDental2813NextDue_AfterUpdate()
If DateDiff("d", [Dental 2813 Next Due], Now() >= 1) Then
Me.Text350 = "Due"
Else
Me.Text350 = ""
If DateDiff("d", [Dental 2813 Next Due], Now() >= 90) Then
Me.Text350 = "Overdue"
Else
Me.Text350 = ""
End If
End If
End Sub

Related

Condition "else" is not allowed? Why?

Why is the else statement is not allowed to have a then or other conditions?
Is it because it is the final condition within the else-if conditions it represents?
I am struggling to understand this concept since I'm a beginner who just learned about variables.
I'm asking this because I received an error with my else statement in the code:
message = 0
condition = 30
if condition <=10
message = “try harder”
elseif
condition <=20 then
message = "Almost learning"
else
condition = <=30 **—This is the line where I get the error message**
message = "Now you’re getting it"
end
print(message)
Would appreciate someone breaking down in laymen terms, why else is not allowed to have < or > or then or other conditions.
else condition = <= 30
(which is the way your code was originally formatted) would be a very unusual feature in a language.
The whole point of else on its own is to execute if none of the other conditions were true. So a condition on the else is absolutely useless.
The Programming in Lua book if statement shows the normal usage:
if op == "+" then
r = a + b
elseif op == "-" then
r = a - b
elseif op == "*" then
r = a*b
elseif op == "/" then
r = a/b
else
error("invalid operation")
end
However, your actual code (when formatted correctly) ends up looking like:
else
condition = <=30
which is correct in terms of the else but unfortunately makes the next line a statement. And this statement is very much incorrect syntax.
Now it may be that you meant to assign 30 to condition but, based on your other lines (that sort of match this as a condition), I suspect not. So it's probably best just to remove that line totally.

How to fix 'if statement with multi conditions' in lua

I use Lua in computercraft to automate the mining. But, my turtle whose program worked very well before, stops if it meets a lava/flowing_lava/water/flowing_water source.
Inside my program, I have a lot of function to manage, for example, the fuel management, the tunnel, the collision with gravel, and .. the detection if the turtle meets a "block".
If the block is just an air block, the turtle continues to advance, elseif the block isn't an air block, the turtle digs this block and doesn't move forward if there is still a block in front of her.
The problem? The four sources which I quoted previously are considered as blocks, and the turtle can't move forward.
I try to fix this problem with multi-condition into the if, but it's doesn't work, the turtle moves forward and dig in any direction.
So I think it's because my way of creating the if isn't good, maybe the syntax (for concatenating many or into () ).
How to solve this issue?
function blockDetection(position, justDetection)
success, detectionBlock = nil
block_name = ""
if position == "right" then
turtle.turnRight()
success, detectionBlock = turtle.inspect()
turtle.turnLeft()
if success then
block_name = detectionBlock.name
if justDetection == true and detectionBlock.name == "minecraft:air" then
block_name = true
elseif justDetection == true and detectionBlock.name ~= "minecraft:air" then
block_name = false
else
end
end
end
end
I think your problem is that you forgot to return block_name. If you omit the return statement, you implicitly return 0 arguments, so trying to access any would give nil values. For example
if blockDetection (position,justDetetcion) then --[[something]] end, would never execute the then-end block, since nil is considered false.
You should also one more thing you should change in your code:
You shouldn't use x==true. If x is a boolean, then if x==true then ... is equivalent to if x then ....
So, your code should look a like this:
function blockDetection(position, justDetection)
success, detectionBlock = nil
block_name = ""
if position == "right" then
turtle.turnRight()
success, detectionBlock = turtle.inspect()
turtle.turnLeft()
if success then
block_name = detectionBlock.name
if justDetection and detectionBlock.name == "minecraft:air" then
block_name = true
elseif justDetection and detectionBlock.name ~= "minecraft:air" then
block_name = false
else
end
end
end
return block_name
end

Find all strings matching REGEX in multiple Word 2013 document and paste into a single, specific Word 2013 document

Spent a week trying to figure this out, so far, so I'm not just jumping here first - and all Microsoft sites tend to focus on Excel which seems to be non-appropriate for what I'm doing:
I'm attempting to use this VBA script to open up multiple WORD files, in succession, run a Find/Selection to grab a specific pattern, and then copy all occurrences into another WORD file.
This code is a mix of something I found online (though can't recall where, at this point) and my own tinkering. I've been able to DEBUG.PRINT the correct output, but no way to continue to move through my file to copy specific lines and then paste them. I feel it has something to do with the .Activate calls:
Sub x()
Dim GetStr(5000) As String
Const wdStory = 4
Const wdExtend = 1
'Set Doc = Documents.Open(FileName:="C:\Users\...\filename.CDS", Visible:=True)
'Set Doc = Documents.Open("C:\Users\...\filename.CDS")
Set MyDialog = Application.FileDialog(msoFileDialogFilePicker)
With MyDialog
.Filters.Clear
.Filters.Add "All WORD File ", "*.CDS", 1
.AllowMultiSelect = True
i = 2 'set to 2 in order to offset the open word window that houses the VBA
If .Show = -1 Then
For Each stiSelectedItem In .SelectedItems
GetStr(i) = stiSelectedItem
i = i + 1
Next
i = i - 1
End If
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open ("C:\Users\...\filename.docx")
For j = 2 To i Step 1
Set objDoc = objWord.Documents.Open(GetStr(j))
'Debug.Print (objWord.Documents(1).Name)
Set objSelection = objWord.Selection
objSelection.Find.Forward = True
objSelection.Find.MatchWildcards = True
objSelection.Find.Text = "DEFINE"
Do While True
objSelection.Find.Execute
Debug.Print (objSelection)
If objSelection.Find.Found Then
objSelection.EndOf wdStory, wdExtend 'get selection
strText = objSelection.Copy 'strText = selection copied to clipboard, no value (like an inline function)
Set selectionToPaste = objWord.Selection 'selectionToPaste is literally the clipboard
'objWord.Documents(2).Activate
'Debug.Print ("->'Activated Window': " + objWord.ActiveDocument.Name)
'Debug.Print ("selectionToPaste = " + selectionToPaste)
selectionToPaste.Paste
'objWord.Documents(1).Activate
objSelection.Find.Execute
Else
objWord.ActiveDocument.Save
objWord.ActiveWindow.Close
Exit Do
End If
Loop
Next
End With
End Sub
OP here - Solved my own problem utilizing a loop.
Sub x()
Dim GetStr(5000) As String
**Dim iCounter As Integer**
Const wdStory = 4
Const wdExtend = 1
'Set Doc = Documents.Open(FileName:="C:\Users\...\filename.CDS", Visible:=True)
'Set Doc = Documents.Open("C:\Users\...\filename.CDS")
Set MyDialog = Application.FileDialog(msoFileDialogFilePicker)
With MyDialog
.Filters.Clear
.Filters.Add "All WORD File ", "*.CDS", 1
.AllowMultiSelect = True
i = 2 'set to 2 in order to offset the open word window that houses the VBA
If .Show = -1 Then
For Each stiSelectedItem In .SelectedItems
GetStr(i) = stiSelectedItem
i = i + 1
Next
i = i - 1
End If
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open ("C:\Users\lidm3b2\Desktop\gar\2.docx")
For j = 2 To i Step 1
Set objDoc = objWord.Documents.Open(GetStr(j))
'Debug.Print (objWord.Documents(1).Name)
Set objSelection = objWord.Selection
objSelection.Find.Forward = True
objSelection.Find.MatchWildcards = True
objSelection.Find.Text = "DEFINE"
**iCounter = 0**
Do While True
**For iLoopCounter = 0 To iCounter Step 1
objSelection.Find.Execute
Next**
Debug.Print (objSelection)
If objSelection.Find.Found Then
objSelection.EndOf wdStory, wdExtend 'get selection
strText = objSelection.Copy 'strText = selection copied to clipboard, no value (like an inline function)
Set selectionToPaste = objWord.Selection 'selectionToPaste is literally the clipboard
objWord.Documents(2).Activate
'Debug.Print ("->'Activated Window': " + objWord.ActiveDocument.Name)
'Debug.Print ("selectionToPaste = " + selectionToPaste)
objWord.Selection.Paste
objWord.Documents(1).Activate
**iLoopCounter = iLoopCounter + 1**
objSelection.Find.Execute
Else
objWord.ActiveDocument.Save
objWord.ActiveWindow.Close 'have to close for the hardcode on "...Documents(1)..." and 2 to work.
Exit Do
End If
Loop
Next
End With
End Sub

Expected Statement End If

I have the following code setup in a form and I'm getting the "Expected Statement" error. My first time doing this and thought I had the syntax correct, what am I missing?
<%
If Trim(oQuote("shipmeth"))="FREIGHT" Then
Response.Write "Freight"
ElseIf Trim(oQuote("shipmeth"))="THRSHLD" Then
Response.Write "Threshold"
End If
%>
When using nested 2-way conditionals, each conditional must be closed by its own End If:
If condition_A Then
action_A
Else
If condition_B Then
action_B
Else
If condition_C Then
action_C
Else
action_D
End If 'condition_C
End If 'condition_B
End If 'condition_A
Only an n-way conditional can be closed with a single End If (because it's just a single conditional):
If condition_A Then
action_A
ElseIf condition_B Then
action_B
ElseIf condition_C Then
action_C
Else
action_D
End If
However, this kind of n-way conditional only makes sense when you're checking different conditions, e.g.
If IsEmpty(a) Then
...
ElseIf b > 23 Then
...
When checking the same variable for different values it's better to use a Select statement as Alex K. suggested:
Select Case foo
Case "a"
'handle foo="a"
Case "b", "d"
'handle foo="b" as well as foo="d"
Case Else
'handle non-matches
End Select
The first statement following the If must be on a new line;
If Trim(oQuote("shipmeth"))="FREIGHT" Then
Response.Write "Freight"
Following conditions can be on the same line but must use ElseIf
ElseIf Trim(oQuote("shipmeth"))="THRSHLD" Then Response.Write "Threshold"
ElseIf ...
I would suggest a more readable Case;
select case Trim(oQuote("shipmeth"))
Case "THRSHLD"
Response.Write "Threshold"
Case "PREMTHRHLD"
Response.Write "Premium Threshold"
...
end select
Which has the additional advantage of only ever executing Trim(oQuote("shipmeth")) once.
I think "else if" should be one word, like elseif
You have nice answers here, I'll append just one more (lightly optimized) alternative.
strTest = Trim(oQuote("shipmeth"))
strResult = "Unexpected"
If strTest ="FREIGHT" Then strResult = "Freight"
If strTest ="THRSHLD" Then strResult = "Threshold"
Response.Write strResult
EDIT
And just to clarify my thought, I hate nested If..Then, unfortunately no GoTo Label in VBScript, therefore above double comparison could be optimized with function.
strResult = "Unexpected"
MyResponse Trim(...), strResult
Response.Write strResult
Sub MyResponse(strIn, strOut)
If strIn = "FREIGHT" Then
strOut = "Freight" : Exit Sub
End If
If strIn = "THRSHLD" Then strOut = "Threshold"
End Sub

Dynamic Depending Lists in Separated WorkSheets in VBA

I'm not really expert in VBA and I have a problem with my code and I don't know how to solve it. (The code is from: http://siddharthrout.wordpress.com/2011/07/29/excel-data-validationcreate-dynamic-dependent-lists-vba/)
I'm working with 8 dynamic dependent lists, and I thought the best way to automate the process and avoid to modify the macro in a future if I modify the lists was a VBA code.
Trying to find the correct code, I'm just working with to lists. For after, apply it for all lists.
I've checked the code and I discovered that there's an error (method 'intersect' of object '_global' failed) because I'm comparing two ranges from a different worksheets.
My code is:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i As Long, LastRow As Long, n As Long
Dim MyCol As Collection
Dim SearchString As String, Templist As String
Application.EnableEvents = False
On Error GoTo Whoa
' Find LastRow in Col A
LastRow = Sheet2.Range("A" & Rows.Count).End(xlUp).Row
If Not Intersect(Target, Sheet2.Columns(1)) Is Nothing Then
Set MyCol = New Collection
' Get the data from Col A into a collection
For i = 2 To LastRow
If Len(Trim(Sheet2.Range("A" & i).Value)) <> 0 Then
On Error Resume Next
MyCol.Add CStr(Sheet2.Range("A" & i).Value), CStr(Sheet2.Range("A" & i).Value)
On Error GoTo 0
End If
Next i
' Create a list for the Data Validation List
For n = 1 To MyCol.Count
Templist = Templist & "," & MyCol(n)
Next
Templist = Mid(Templist, 2)
Range("A2").ClearContents: Range("A2").Validation.Delete
' Create the Data Validation List
If Len(Trim(Templist)) <> 0 Then
With Range("A2").Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=Templist
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End If
' Capturing change in cell A2
ElseIf Not Intersect(Target, Range("A2")) Is Nothing Then
SearchString = Range("A2").Value
Templist = FindRange(Sheet2.Range("A2:A" & LastRow), SearchString)
Range("B2").ClearContents: Range("B2").Validation.Delete
If Len(Trim(Templist)) <> 0 Then
' Create the DV List
With Range("B2").Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=Templist
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End If
End If
LetsContinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
' Function required to find the list from Col B
Function FindRange(FirstRange As Range, StrSearch As String) As String
Dim aCell As Range, bCell As Range, oRange As Range
Dim ExitLoop As Boolean
Dim strTemp As String
Set aCell = FirstRange.Find(what:=StrSearch, LookIn:=xlValues, lookat:=xlWhole, SearchOrder:= _
xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
ExitLoop = False
If Not aCell Is Nothing Then
Set bCell = aCell
strTemp = strTemp & "," & aCell.Offset(, 1).Value
Do While ExitLoop = False
Set aCell = FirstRange.FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
strTemp = strTemp & "," & aCell.Offset(, 1).Value
Else
ExitLoop = True
End If
Loop
FindRange = Mid(strTemp, 2)
End If
End Function
Into the Sheet1, I just want the cells to select the list options and into the Sheet2, I want the all dynamic and dependent lists.
Is there any possibility to compare two ranges from a different worksheets using these algorithm? Or an alternative code to create a pick list for 8 depending and dynamic lists?
I am going to turn you to this page that describes dynamic dependent list usage very well.
Dynamic Dependent Lists
Perhaps you don't need VBA at all, unless you have to alter these on the fly, or based on some other variable. It's always best to use Excel's built-in functionality first, and code 2nd.
In case you are wandering, you can get around having lists on two different sheets by setting the named range scope to the entire workbook.
Edit: Adding answer to direct VBA error.
Since you didn't say, not sure if your Intersect is breaking here:
If Not Intersect(Target, Sheet2.Columns(1)) Is Nothing Then
but I think it is. Try this:
If Not Intersect(Target, Columns(1).EntireColumn) Is Nothing Then