This question already has answers here:
Trouble with InputBoxes
(5 answers)
Closed 4 months ago.
I have found the Macro for MS Word (as below) from the website https://excelchamps.com/blog/vba-code-search-google-chrome/
Sub GoogleSearch()
Dim chromePath As String
Dim search_string As String
Dim query As String
query = InputBox("Please enter the keywords", "Google Search")
search_string = query
search_string = Replace(search_string, " ", "+")
chromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Shell (chromePath & " -url http://www.google.com/search?hl=en&q=" & search_string)
End Sub
I would like to close the Message Box when I mistakenly press the Macro button/ran this Macro. However, whatever I press (Yes/No/Close that msgbox), it ignored all of these choices and automatically search what I type in the msgbox.
I tried to add the below code but it doesn't work.
If MsgBoxResult = vbCancel Then
Exit Sub
Else
I am junior to Word Macro. May I ask if anyone have any suggestions to make the msgbox work? (press cancel or close the window and then don't open Chrome and search automatically) Thank you for your kind attention.
Just have a look to the official documentation for InputBox
Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a String containing the contents of the text box.
(...)
If the user chooses OK or presses ENTER, the InputBox function returns whatever is in the text box. If the user chooses Cancel, the function returns a zero-length string ("").
So (in opposite to MsgBox), the InputBox always returns a String, while vbCancel is a number. You will need to check if the return value is the empty string. Note that you can't distinguish between "the user didn't enter something and pressed [OK]" or "the user pressed [Cancel]".
If MsgBoxResult = "" Then Exit Sub
Related
How do I “Call” Vba’s MsgBox function? Is this the same as just using the actual function itself? I want to make a MsgBox function that returns the date and time.
Like this:
MsgBox "It is now " & Format(Now, "yyyy-mm-dd hh:nn"), vbInformation + vbOKOnly, "Current Date and Time"
Is this the same as just using the actual function itself ?
Yes, you may consider it as a regular function in VBA.
I want to make a MsgBox function that returns the date and time
The MsgBox function is for displaying questions or warnings and etc. to users and returning answers like Yes, No, Cancel and etc. Strictly speaking the function displays a message in a dialog box, waits for the user to click a button, and returns an Integer indicating which button the user clicked.
If you need to let users enter any information on on the dialog box you need to use the InputBox function instead. It displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a String containing the contents of the text box. You may then parse the date entered on the dialog box and use it in the code. For example:
Dim Message, Title, Default, MyValue
Message = "Enter a value between 1 and 3" ' Set prompt.
Title = "InputBox Demo" ' Set title.
Default = "1" ' Set default.
' Display message, title, and default value.
MyValue = InputBox(Message, Title, Default)
' Display dialog box at position 100, 100.
MyValue = InputBox(Message, Title, Default, 100, 100)
The error message continues with:
"*The expression may not result in the name of a macro, the name of a user-defined function, or [Event Procedure]."
"*There may have been an error evaluating the function, event, or macro."
This database was written by an employee who retired years ago and unfortunately I am now stuck with it. It was working last week and of course when it stopped working today. I am not sure where to even start looking or how to debug in VBA. When a user enter data in the fields and click on Print button, I believe the data gets populated in the data source and then it will print a report/receipt. The print button call the cmdPrintReceipt_Click() procedure. Can someone give me some pointers or how to debug in VBA? Much appreciated and happy holidays!
Pasting the code here:
Option Compare Database
Option Explicit
Dim OkPass As Integer, message As String, Response As Integer
Dim nAmount As Integer
Dim Conn As New ADODB.Connection
Dim RS2 As ADODB.Recordset
Dim Total As Long 'Hold receiptNumber for ReceiptLine
Private Sub cmdNoAdd_Click() 'close window without adding a new reacord
'Use the msgbox function to see if user wants to exit this form w/o adding new receipt
Dim Msg, Style, Title, respons
Msg = "Close this window without saving this receipt?"
Style = vbYesNo + vbQuestion + vbDefaultButton2 'Define buttons of message box
Title = "Exit without adding a receipt?" 'Title of the message box
respons = MsgBox(Msg, Style, Title)
If respons = vbYes Then 'User chose Yes DO NOT ADD the Record
DoCmd.Close
Else 'User chose No close the message box and leave frmReceipt Open
End If
End Sub
Private Sub Form_Load()
'Clear Total
Total = 0
End Sub
'****************************************************************************************
' Main procedure for the form, check first all required fields filled in
' then Add new records and print receipts.
'****************************************************************************************
Private Sub cmdPrintReceipt_Click()
'Check if all filled in, then
'Just call the AddReceipt Function
DoNotClose 'function
If OkPass <> 9 Then
Response = MsgBox(message, vbOKOnly, "Information Missing")
'return focus to the frmReceipt
txtFirstName.SetFocus
Exit Sub
Else
' Add the new Receipt record
Me.lblNoAdd.Visible = False
Me.cmdNoAdd.Visible = False 'you can't escape after printing receipt.
AddAReceipt ' call AddReceipt function
MsgBox "Please confirm the information you entered is correct", vbOKOnly
ShowPrint3Button
'cmdPrint3Button print 3 copies of receipt
End If
Exit Sub
End Sub
If it worked for years without errors before, I doubt debugging will help.
The db might be corrupted. Try the following steps:
see if VBA compiles
compact and repair the db
if not successfull, create a new blank db, and imort all objects from the old one.
Also, when you get the error message, you can press Ctrl+Break and arrive on the exact line that causes the error. Good luck ;-)
I'm trying to do what, I think, ought to be the simplest of things, but I can't get it to work. i have an MS Word document with a number of legacy drop-down and text fields:
The first option in each drop-down is "Select ...", and if a user tabs out of one of the drop-downs without choosing something other than the first "Select ...", I want a msgbox to appear to tell them to make a selection, which works. What doesn't work, is that after the user dismisses the msgbox, I want the insertion point to return to the drop-down that they didn't select.
I understand that VBA has "timing issues", and from what I've read, one way to address these timing issues is to call the "return" macro from the validation macro. So I've written two macros:
Sub Validate()
' Dim strBookmark As String
' strBookmark = Selection.Bookmarks(1).Name
10: If (bool_debug) Then MsgBox ("NotSelected() - 10: strBookmark = " & strBookmark)
With ActiveDocument
If (strBookmark = "Locality") Then
Call Salary_Step
ElseIf (strBookmark = "Series") Then
20: If (bool_debug) Then MsgBox ("NotSelected() - 20: .FormFields(strBookmark).Name = " _
& .FormFields(strBookmark).Name)
If ((Len(.FormFields(strBookmark).Result) <> 4) Or (Not IsNumeric(.FormFields(strBookmark).Result))) Then _
MsgBox ("Please enter a 4 digit number.")
Call GoBackToPrevious(.FormFields(strBookmark).Name)
ElseIf (.FormFields(strBookmark).DropDown.Value = 1) Then
MsgBox ("Please select a " & Replace(Selection.FormFields(strBookmark).Name, "_", " ") & ".")
Call GoBackToPrevious(.FormFields(strBookmark).Name)
End If
End With
End Sub
and
Sub GoBackToPrevious(strPreviousField)
10: If (bool_debug) Then MsgBox ("GoBacktoPrevious - 10: strPreviousField = " & strPreviousField)
ActiveDocument.Bookmarks(strPreviousField).Range.Fields(1).Result.Select
End Sub
But when I tab out of any of the form fields, the insertion point jumps to the next form field and not back to the one that I just tabbed out of.
I know from the debug code that GoBackToPrevious is being passed the name of the current form field, but MS Word advances to the next field regardless.
I'd really appreciate it if someone can tell me how make MS Word return to and select the drop-down the user did not select appropriately instead of jumping to and selecting the next form field in the document.
Thank you.
P James Norris
EDIT:
Based on #TimothyRylatt comments, I have modified my macro and when they're called.
I have edited Validate as above (commenting out the Dim the strBookmark assignment, and I call it "on entry" to the next form field.
strBookmark is Dimed on the module's declaration section:
Option Explicit
Const bool_debug As Boolean = True
Const str_password As String = "###" ' I have a different password
Public strBookmark As String
and "on exit" from the "current" form field, I attempt to store the "current" bookmark name:
Sub StoreBookmark()
strBookmark = Selection.Bookmarks(1).Name
10: If (bool_debug) Then MsgBox ("StoreBookmark() - 10: strBookmark = " & strBookmark)
End Sub
which I call from the current form field "on exit".
But when I tab out of the current form field to the next form field, the insertion point doesn't go back to the "current" but instead stays in the next form field.
Anyone have any other suggestions/insights?
Thanks,
P James Norris
I've looked all over for the solution to this, finally figured I would just ask.
I have a form I've created in Word. It is not a formal "userform1" type form as in a VB project. It is written all in the Word document itself.
I am going to have a lead person email my this report every evening. I have been able to successfully have the user click the submit button and email the form (MS Word (NighlyReport.DOCM)).
In the final stages now, I am "trying with no success" to validate all of my textboxes with no luck.
I want to make each textbox required and if the user does not enter a value, I would like the "setFocus" to return the user back to the textbox. Since I am not using an official "userform" I do not seem to have this method available to me - to return the user back to the form. I have tried
_Change
_GotFocus
_LostFocus
_KeyPress
_MouseDown
All of these work fine as long as I am inside the textbox. None of them sends the user back to it.
Does anybody know a way to do this. I wanted a straightforward nice looking form to fill out and attach to outlook (which I've done). Just need to validate the textboxes. I would be willing to validate all of them with a commandbutton as well, but still cannot get the focus back to the textbox that was not filled out by the user.
For the sake of simplicity, I am posting just two textboxes here and my basic validation that is not working. To be clear, I am not using the userform grid, maybe that makes all of this impossible to do.
Thanks ahead:
Private Sub txt1_Change()
If txt1.Value = "" Then
MsgBox "need your input"
Else
Exit Sub
End If
End Sub
Private Sub txt2_Change()
If txt2.Value = "" Then
MsgBox "need your input"
Else
Exit Sub
End If
End Sub
Try something along the lines of:
Dim iShp As InlineShape, StrOut As String
For Each iShp In ActiveDocument.InlineShapes
With iShp
If .Type = wdInlineShapeOLEControlObject Then
If .OLEFormat.ClassType Like "Forms.TextBox.*" Then
If Trim(.OLEFormat.Object) = "" Then StrOut = StrOut & vbCr & .OLEFormat.Object.Name
End If
End If
End With
Next
If StrOut <> "" Then
MsgBox "The following controls have not been completed: " & StrOut
Exit Sub
End If
I have solid experience in C++ but am still getting used to the syntax of VBA and I think that's what's tripping me up in my code.
What I'm trying to do is have a button that asks the user for a name. If the name entered is in column B, then tell the user the name was found and select where it is (no problem with this). If the name is not found, then ask if the user wants to try another name (no problem with this, either).
Where I'm having trouble is with the "Cancel" buttons. At any time, I want the user to be able to hit "Cancel" and immediately stop the loop, but stay in the sub because I'll be adding to this later.
Here's the code:
Dim inputName As String
Dim row As Integer
Dim i As Integer
Dim tryAgainResponse As Integer
tryAgainResponse = vbOK
'Ask user for name they would like to replace'
inputName = InputBox("What is the name of the person you would like to find? (First Last)")
'Find the row that the name is located and tell the user where it is'
Do While tryAgainResponse = vbOK
For i = 1 To 1000
If Cells(i, 2).Value = inputName Then
MsgBox ("Found the name! It's located at cell B" & i & ".")
ActiveSheet.Cells(i, 2).Select
tryAgainResponse = 0
Exit Do
End If
Next i
tryAgainResponse = MsgBox("We didn't find the name you were looking for. Please try again.", vbOKCancel)
If tryAgainResponse = vbCancel Then
Exit Do
End If
inputName = InputBox("What is the name of the person you would like to find? (First Last)")
Loop
I've tried plenty of things, but the main error is when you hit cancel for the first MsgBox, it tells you the name was found in the first blank square.
Any help or suggestions would be greatly appreciated! This is my first VBA program, so it's not the prettiest, but it's definitely a lot of fun. Thanks!
I'm not sure if I'm understanding what you're asking for, and I can't comment for clarification, but I think your hang up is that when you click cancel on the INPUT box, your input box is returning a blank string, and the rest of your code is then finding a blank cell.
Use the Application.Input Method, declare your input string as a variant, and test if it is false. If it is, use an Exit Sub to exit the macro. You could also test if your input string = "" and then exit the macro if true with the code you have.
From MrExcel
There are 2 versions of InputBox in VBA.
The InputBox Function is called without an object qualifiier and returns the contents of the text box or a zero-length string ("") if the user clicks Cancel.
The InputBox Method is a member of the Application object, so it is called by using Application.InputBox. It returns the contents of the text box or False if the user clicks Cancel. It is more versatile than the InputBox Function because it has a Type argument which specifies the return data type.
The function InputBox() will return an empty string if cancelled. The empty string will compare equal to the first cell that is empty.
Here's the doc of the function: http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx