My original question was how to use a function's output in an if-->then statement, and Shai's help was very helpful (here: Using an output of aformula in another).
What I would like to do now, though, is to use this function in a sub. So I have this sub (which is not complete for now):
Private Sub CommandButto1_click()
Dim answer As Integer
Dim Response As VbMsgBoxResult
Dim late As VbMsgBoxResult
answer = MsgBox("Price for only one product?", vbYesNoCancel + vbQuestion, "Payment")
If answer = vbYes then
late = MsgBox("Is the customer late and has to be charged extra?", vbQuestion + vbYesNoCancel)
If late = vbYes then
MsgBox "mergesize function here"
End If
End If
End Sub
It works fine as it is, but where it says - MsgBox "mergesize function here" is where I would like to add my function that looks like this:
Public Function MergeSize(r As Range) As Long
MergeSize = r(1).MergeArea.Cells.Count
If MergeSize <= 10 Then
MergeSize = MergeSize * 70
Else
MergeSize = MergeSize * 65
End If
End Function
Another side question is can I send the output of the function to null and have it only displayed in a msgbox?
Try something like the code below.
Iv'e marked where I added the code that calls the Function MergeSize. I've used Range("B2") as the Merged Range.
Code
Private Sub CommandButto1_click()
Dim answer As Integer
Dim Response As VbMsgBoxResult
Dim late As VbMsgBoxResult
answer = MsgBox("Price for only one product?", vbYesNoCancel + vbQuestion, "Payment")
If answer = vbYes Then
late = MsgBox("Is the customer late and has to be charged extra?", vbQuestion + vbYesNoCancel)
If late = vbYes Then
'===== Added the 3 lines below =====
Dim ExtraCharge As Long
ExtraCharge = MergeSize(Range("B2")) '<-- Range("B2") is a Merged Cells
' === Ver 2.0 - to use with ActiveCell ===
ExtraCharge = MergeSize(ActiveCell) '<-- ActiveCell is a Merged Cells
MsgBox "Extra Charge is " & ExtraCharge
End If
End If
End Sub
Related
I am having trouble coding this VBA code. I need the code to ask the user if they want data or a graph. If the user selects Yes From there, I need to the code to look at the selected input and see if that input is a valid sheet name. If not, the input box will display again until valid sheet name. If the sheet is valid, then I need the sheet to be selected or show up whenever the user enters a valid value. I hope that makes sense.
For example, if the user enters (10-1) that is a valid sheet or (1-1) valid sheet but if it is (14-1) or (a-a) that is not a valid sheet.
Note I have not gotten to the graphing part yet, so do not worry about if the user selects no yet. Can someone get me in the correct direction?
Sub InputValidation()
Dim str As String
Dim inp As String
Dim ws As Worksheet
str = MsgBox("Do you want to select a dataset (Yes) or a Graph (No)", vbQuestion + vbYesNo)
If str = vbYes Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
If MsgBox("Do you really want to QUIT", vbYesNo + vbQuestion) = vbYes Then MsgBox "Thank You Goodbye"
Exit Sub
End If
ElseIf inp = "#-#" Or "##-#" Then
If Sheets(ws).Name = inp Then
Worksheets(inp).Activate
End If
Else
MsgBox "This load and test cannot be found"
If str = vbNo Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
If MsgBox("Do you really want to QUIT", vbYesNo + vbQuestion) = vbYes Then MsgBox "Thank You Goodbye"
Exit Sub
End If
End If
End If
End Sub
Please make sure you close all you if statements when using indentation?
The way you have now set it implies that the last End if is covering the entire str = vbYes scope, i.e. if str = vbNo nothing happens?
Sub InputValidation()
Dim str As String
Dim inp As String
Dim ws As Worksheet
str = MsgBox("Do you want to select a dataset (Yes) or a Graph (No)", vbQuestion + vbYesNo)
If str = vbYes Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
If MsgBox("Do you really want to QUIT", vbYesNo + vbQuestion) = vbYes Then MsgBox "Thank You Goodbye"
Exit Sub
'End If
ElseIf inp = "#-#" Or "##-#" Then
If Sheets(ws).Name = inp Then
Worksheets(inp).Activate
End If
Else
MsgBox "This load and test cannot be found"
End If '=> added this End If as it will otherwise skip to end of sequence
ElseIf str = vbNo Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
If MsgBox("Do you really want to QUIT", vbYesNo + vbQuestion) = vbYes Then MsgBox "Thank You Goodbye"
Exit Sub
End If
End If
End Sub
I also think your below line is incorrect?
ElseIf inp = "#-#" Or "##-#" Then
It will give a Type Mismatch error? (Error 13)
You could contemplate using a regex for this assessment or simply use something like the below?
ElseIf inp like "*-*" Then
Which would also do the trick?
The subsequent statement tries to select the Worksheet but that won't work as you have not set the ws object anywhere? So the below line is incorrect in many ways:
If Sheets(ws).Name = inp Then
Please see below code that will give you a good base to start from?
This would also get rid of the unnecessary inp = "#-#" comparison
Private Function SheetExists(name As String) As Boolean
SheetExists = False
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.name = name Then SheetExists = True: Exit Function
Next
End Function
Private Function ConfirmEndSub()
ConfirmEndSub = MsgBox("Do you really want to QUIT", vbYesNo + vbQuestion)
If ConfirmEndSub = vbYes Then
MsgBox "Thank You Goodbye"
End If
End Function
Sub InputValidation()
Dim str As String
Dim inp As String
Dim ws As Worksheet
str = MsgBox("Do you want to select a dataset (Yes) or a Graph (No)", vbQuestion + vbYesNo)
If str = vbYes Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
Reply = ConfirmEndSub
If Reply = vbYes Then Exit Sub
ElseIf SheetExists(inp) Then
Worksheets(inp).Activate
Else
MsgBox "This load and test cannot be found"
End If
ElseIf str = vbNo Then
inp = InputBox("Please enter a load value (10 or a load and trial (10-1)")
If StrPtr(inp) = 0 Then
Reply = ConfirmEndSub
If Reply = vbYes Then Exit Sub
End If
End If
End Sub
This leaves entirely out of consideration that depsite the initial vbYesNo answer the user will always get the input box? Not sure if that is the intention, but alas that is how it was written.
One other consideration is that if the user selects not to Quit, the call is not returning to the request for input? => I.e. it is still ending the routine...
I am trying to run a loop where for each account in a range the account number is sent out to a program to search for data. This data is input to another Excel sheet, formatted, and then printed to PDF. This data can only be fetched by one account at a time, so I need it to run through and after saving one pdf to either clear the data and do it again for the next account etc. This process can take a while and so what I am trying to do is create a percentage complete cell.
Is there a way to recognize how many times through the loop it needs to run (say 10) and then update a cell saying we are on loop 1 of 10, 2 of 10, etc.
Here is the code I am running right now:
Public Sub Eligibility()
Dim a As Range, ws As Worksheet
Set ws = ThisWorkbook.Sheets("Starting Page")
'************* This is the loop to check the cells and set the offset value as elgible or ineligible**********
For Each a In ws.Range("G9:G29").Cells
If a.Value = Eligible Then
a.Offset(0, -1).Value = AccountNumber(a.Value)
Data_Import
End If
Next a
'************* Question if we will printscreen**********
Dim AnswerYes As String
Dim AnswerNo As String
AnswerYes = MsgBox("Do you want to print all eligible class action reports?", vbQuestion + vbYesNo, "User Response")
If AnswerYes = vbYes Then Print_PDF
End Sub
G9:G29 is the range and so I wonder if the number could look at that range and tell how many instances of "eligible" there is for the denominator on the count.
Run through the loop adding each of the eligible cells to a VBA collection, then you can get the count of items in the collection (total eligible cells) then use a FOR loop to loop through the items in the collection doing the actual work. percentage complete will be i/count
Something like this (totally untested!)
Public Sub Eligibility()
Dim a As Range, ws As Worksheet
Dim oEligibleCells As VBA.Collection
Dim i As Long
Set ws = ThisWorkbook.Sheets("Starting Page")
'************* This is the loop to check the cells and set the offset value as elgible or ineligible**********
Set oEligibleCells = New VBA.Collection
For Each a In ws.Range("G9:G29").Cells
If a.Value = Eligible Then
Call oEligibleCells.Add(a)
End If
Next a
For i = 1 To oEligibleCells.Count
Set a = oEligibleCells(i)
a.Offset(0, -1).Value = AccountNumber(a.Value)
Data_Import
Application.StatusBar = i / oEligibleCells.Count * 100 & " percent done"
Next i
'************* Question if we will printscreen**********
Dim AnswerYes As String
Dim AnswerNo As String
AnswerYes = MsgBox("Do you want to print all eligible class action reports?", vbQuestion + vbYesNo, "User Response")
If AnswerYes = vbYes Then Print_PDF
End Sub
The question asks to create a loop asking an initial yes/no question: are you saving for college? If no, the loop should end. If Yes, the code should ask the user to answer: Years until college starts, annual college payment, and another child? If the answer for another child is yes, the loop should start over. If the answer is no, the loops should end. I am having trouble putting the pieces together.
I have tried using yes/no message boxes but run into the issue of changing to numerical answers and getting the loop to start over.
Ans = MsgBox("Saving for college?", vbYesNo)
If Ans = vbNo Then Exit Sub
If Ans = vbYes Then
Dim myvalue As Integer
myvalue = InputBox("Years until college starts?")
Dim value As Integer
value = InputBox("Annual College Payments?")
Ans = MsgBox("Another child?")
Ans = MsgBox(msg, vbYesNo)
If Ans = vbYes**strong text** Then
Option Explicit
Sub Questions()
Dim ans As Long
Dim yearsToCollegeStart As String, annualCollegePayment As String
Do
If MsgBox("Saving for college", vbYesNo + vbQuestion) = vbNo Then Exit Sub
yearsToCollegeStart = InputBox("Years until college starts?")
annualCollegePayment = InputBox("Annual College Payments?")
ans = MsgBox("Another child", vbYesNo + vbQuestion)
Loop while ans = vbYes
End Sub
The below code may help you. However have in mind that you have to handle user answers (yes, no, close, cancel) in both message boxes & inputboxes.
Option Explicit
Sub test()
Dim Ans1 As Long, value1 As String, value2 As String, Ans2 As String
Ans1 = MsgBox("Saving for college", vbYesNo + vbQuestion)
If Ans1 = vbNo Then
Exit Sub
ElseIf Ans1 = vbYes Then
value1 = InputBox("Years until college starts?")
value2 = InputBox("Annual College Payments?")
Ans2 = MsgBox("Another child", vbYesNo + vbQuestion)
If Ans2 = vbYes Then
'Code
ElseIf Ans2 = vbNo Then
'Code
End If
End If
End Sub
I am trying to generate a popup that closes after a given WaitTime in seconds.
I consulted this link and this link.
I tried to apply the method from "VBA Excel macro message box auto close"; my code is the following:
Sub TestSubroutine()
Dim TemporalBox As Integer
Dim WaitTime As Integer
Dim WScriptShell As Object
Set WScriptShell = CreateObject("WScript.Shell")
WaitTime = 1
TemporalBox = WScriptShell.Popup("The message box will close in 1 second.", _
WaitTime, "File processed")
End Sub
The popup is displayed but it never closes after one second.
Edit #1
Based on #Skip Intro comment, I have updated the code:
Sub TestSubroutine()
Dim WaitTime As Integer
WaitTime = 1
CreateObject("WScript.Shell").Popup "The message box will close in 1 second.", _
WaitTime, "File processed"
End Sub
However this does not solve the original issue, the popup does not close after 1 second.
Edit #2
This is the code suggested by #Glitch_Doctor, however it still doesn't work:
Sub TestSubroutine()
Dim TemporalBox As Integer
Dim WaitTime As Integer
Dim WScriptShell As Object
Dim test
Set WScriptShell = CreateObject("WScript.Shell")
WaitTime = 1
Select Case TemporalBox = WScriptShell.Popup("The message box will close in 1 second.", _
WaitTime, "File processed")
Case 1, -1
End Select
End Sub
I finally found a very simple solution - credits to #Orphid, see his answer in the following thread.
I did not solve the specific issue related to my original code, but I managed to create a PopUp that closes after a specified period of time. The code is the following:
Sub subClosingPopUp(PauseTime As Integer, Message As String, Title As String)
Dim WScriptShell As Object
Dim ConfigString As String
Set WScriptShell = CreateObject("WScript.Shell")
ConfigString = "mshta.exe vbscript:close(CreateObject(""WScript.Shell"")." & _
"Popup(""" & Message & """," & PauseTime & ",""" & Title & """))"
WScriptShell.Run ConfigString
End Sub
This works just fine.
Another approach (if your would not work at all).
Create a new userform named frm_Popup and add a label there named lbl_Message. Add the following void to userform code:
Public Sub StartProcess(iTime As Integer)
Me.lbl_Message.Caption = "The message box will close in " & iTime & " second(s)."
End Sub
then in your module:
Sub ShowMessage()
Dim iTimeToWait As Integer
iTimeToWait = 2
With frm_Popup
.Show False
Call .StartProcess(iTimeToWait)
End With
Application.OnTime Now + TimeValue("00:00:" & iTimeToWait), "HidePopup"
End Sub
Private Sub HidePopup()
Unload frm_Popup
End Sub
You're just missing the Select Case:
WaitTime = 1
Select Case TemporalBox = WScriptShell.Popup("The message box will close in 1 second.", _
WaitTime, "File processed")
Case 1, -1
End Select
I tested and it works...
Below code work for me, I added a 2-sec delay before the popup message appears. After 4-sec it auto disappear. I learn it from Mr. Dinesh Kumar Takyar. He added a 5-sec delay b4 popup appears. His youtube link
https://www.youtube.com/watch?v=x1nmqVRrq-Q&list=PLwC8syx0i_6nHjAogOm9m4oGBq40YHkXV&index=4
I think the key issue is you need a delay for the popup timer to work. Maybe the Excel application needs to run for a while b4 the popup appears.
Option Explicit
Const PopUpTime As Integer = 4
Sub ShellMessageBox()
Dim MsgBoxWithTimer As Integer
MsgBoxWithTimer=CreateObject("WScript.Shell").Popup("Put your message here", PopUpTime, _
"Notice!", 0)
End Sub
Sub startTimer()
Application.OnTime Now + TimeValue("00:00:02"), "ShellMessageBox"
End Sub
Private Sub Workbook_Open()
startTimer
End Sub
The following code works for me:
Sub TimeBasedPopUp()
Dim WaitTime As Integer
WaitTime = 1
Select Case CreateObject("WScript.Shell").Popup("The message box will close in 1 second.",_
WaitTime, "MS Excel")
Case 1, -1
End Select
End Sub
I am trying to generate a popup that closes after a given WaitTime in seconds.
I consulted this link and this link.
I tried to apply the method from "VBA Excel macro message box auto close"; my code is the following:
Sub TestSubroutine()
Dim TemporalBox As Integer
Dim WaitTime As Integer
Dim WScriptShell As Object
Set WScriptShell = CreateObject("WScript.Shell")
WaitTime = 1
TemporalBox = WScriptShell.Popup("The message box will close in 1 second.", _
WaitTime, "File processed")
End Sub
The popup is displayed but it never closes after one second.
Edit #1
Based on #Skip Intro comment, I have updated the code:
Sub TestSubroutine()
Dim WaitTime As Integer
WaitTime = 1
CreateObject("WScript.Shell").Popup "The message box will close in 1 second.", _
WaitTime, "File processed"
End Sub
However this does not solve the original issue, the popup does not close after 1 second.
Edit #2
This is the code suggested by #Glitch_Doctor, however it still doesn't work:
Sub TestSubroutine()
Dim TemporalBox As Integer
Dim WaitTime As Integer
Dim WScriptShell As Object
Dim test
Set WScriptShell = CreateObject("WScript.Shell")
WaitTime = 1
Select Case TemporalBox = WScriptShell.Popup("The message box will close in 1 second.", _
WaitTime, "File processed")
Case 1, -1
End Select
End Sub
I finally found a very simple solution - credits to #Orphid, see his answer in the following thread.
I did not solve the specific issue related to my original code, but I managed to create a PopUp that closes after a specified period of time. The code is the following:
Sub subClosingPopUp(PauseTime As Integer, Message As String, Title As String)
Dim WScriptShell As Object
Dim ConfigString As String
Set WScriptShell = CreateObject("WScript.Shell")
ConfigString = "mshta.exe vbscript:close(CreateObject(""WScript.Shell"")." & _
"Popup(""" & Message & """," & PauseTime & ",""" & Title & """))"
WScriptShell.Run ConfigString
End Sub
This works just fine.
Another approach (if your would not work at all).
Create a new userform named frm_Popup and add a label there named lbl_Message. Add the following void to userform code:
Public Sub StartProcess(iTime As Integer)
Me.lbl_Message.Caption = "The message box will close in " & iTime & " second(s)."
End Sub
then in your module:
Sub ShowMessage()
Dim iTimeToWait As Integer
iTimeToWait = 2
With frm_Popup
.Show False
Call .StartProcess(iTimeToWait)
End With
Application.OnTime Now + TimeValue("00:00:" & iTimeToWait), "HidePopup"
End Sub
Private Sub HidePopup()
Unload frm_Popup
End Sub
You're just missing the Select Case:
WaitTime = 1
Select Case TemporalBox = WScriptShell.Popup("The message box will close in 1 second.", _
WaitTime, "File processed")
Case 1, -1
End Select
I tested and it works...
Below code work for me, I added a 2-sec delay before the popup message appears. After 4-sec it auto disappear. I learn it from Mr. Dinesh Kumar Takyar. He added a 5-sec delay b4 popup appears. His youtube link
https://www.youtube.com/watch?v=x1nmqVRrq-Q&list=PLwC8syx0i_6nHjAogOm9m4oGBq40YHkXV&index=4
I think the key issue is you need a delay for the popup timer to work. Maybe the Excel application needs to run for a while b4 the popup appears.
Option Explicit
Const PopUpTime As Integer = 4
Sub ShellMessageBox()
Dim MsgBoxWithTimer As Integer
MsgBoxWithTimer=CreateObject("WScript.Shell").Popup("Put your message here", PopUpTime, _
"Notice!", 0)
End Sub
Sub startTimer()
Application.OnTime Now + TimeValue("00:00:02"), "ShellMessageBox"
End Sub
Private Sub Workbook_Open()
startTimer
End Sub
The following code works for me:
Sub TimeBasedPopUp()
Dim WaitTime As Integer
WaitTime = 1
Select Case CreateObject("WScript.Shell").Popup("The message box will close in 1 second.",_
WaitTime, "MS Excel")
Case 1, -1
End Select
End Sub