简体   繁体   中英

Message box popup query

I have the following code in an excel spreadsheet, however is there a way to prevent the message box popping up if the lookup value in the range is a blank cell? Also, is there a way to get the message box to pop up in a psecified area on the sheet. Thanks in advance for any help!

Private Sub Worksheet_SelectionChange(ByVal Target As Range)   
If Not Intersect(Target, Range("facops")) Is Nothing Then     
On Error Resume Next     
MsgBox WorksheetFunction.VLookup(Target.Offset(0, 0), Worksheets("Options").Range("Options"), 3), vbOKOnly, "Option Information"     
On Error GoTo 0   
End If 
End Sub

In order to prevent the pop-up for blank cells you can check the result of your VLookup prior to presenting it in a message box:

If Not IsEmpty(WorksheetFunction.VLookup(.......)) Then
   MsgBox ...
End If

A message box cannot be shown in a specific area of the screen. Yet, you can create a form instead, show the form with the error message, and show this form on the screen whereever you want. The following code example will show the form in the center of your Excel:

frmMessageBox.StartUpPosition = 0
frmMessageBox.Left = Application.Left + Application.Width / 2 - frmMessageBox.Width / 2
frmMessageBox.Top = Application.Top + Application.Height / 2 - frmMessageBox.Height / 2
Load frmMessageBox
frmMessageBox.Show

This example will show the form in the lower right corner of Excel:

frmMessageBox.Left = Application.Left + Application.Width - frmMessageBox.Width
frmMessageBox.Top = Application.Top + Application.Height - frmMessageBox.Height

I'd store the lookup-result in a string, and only display the messagebox if the result is non-empty. You may want to check if vlookup actually succeeds at finding a result too, but the method is much the same:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Dim s As String
  If Not Intersect(Target, Range("facops")) Is Nothing Then
    On Error Resume Next
      s = WorksheetFunction.VLookup(Target.Offset(0, 0), Worksheets("Options").Range("Options"), 3)
      If s <> "" Then
        MsgBox s, vbOKOnly, "Option Information"
      End If
    On Error GoTo 0
  End If
End Sub

Positioning the messagebox is more tricky, a quick google shows eg this thread on the Mr. Excel forums which provides some code for doing what you ask for. I haven't tried it out myself, so no guarantee that it will work, but unless you want to create a custom form or use an inputbox instead (both of which it is possible to position), that is my best suggestion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM