简体   繁体   中英

Excel VBA Macro: Searching For Blank From Selection

I am trying to search through a selection from a table, find a value and then return a specific result.

The conditions I am trying are:

  1. IF 'Name' = blank, return "N / A".
  2. IF 'Result' = blank, OR "N/A", return "N / A".
  3. IF 'Count' = 0, return "No", ELSE "Yes".

The code I have tried so far is as follows:

Sub DoStuffIfNotEmpty()

  Set M = Selection

  If Not IsEmpty(M) Then
     MsgBox "I'm not empty!"

  Else
     MsgBox "Empty Value"

  End If

End Sub

Also for reference, here is the test table I have created:

Reference Image

Test() sets up the worksheet and cells to examine -- if you want to work down a list of cells you can do it here -- and calls DoStuffIfNotEmpty , which examines the Name, Result and Count columns in order. Its not even close to being elegant but there you go...

Sub Test()
    Dim cWorksheet As Worksheet
    Dim CRange As Range

    Set cWorksheet = ActiveWorkbook.Sheets("Sheet1")
    Set CRange = cWorksheet.Range("A2:C2")
    MsgBox DoStuffIfNotEmpty(cWorksheet, CRange), vbOKOnly
End Sub

Function DoStuffIfNotEmpty(CurrWorksheet As Worksheet, CurrRange As Range) As String

    CurrWorksheet.Select
    CurrRange.Select

    Set m = Selection

    If m.Cells(1, 1) = "" Or IsNull(m.Cells(1, 1)) Then
        retmsg = "N/A"
    Else
        If m.Cells(1, 2) = "" Or IsNull(m.Cells(1, 2)) Or m.Cells(1, 2) = "N/A" Then
            retmsg = "N/A"
        Else
            If m.Cells(1, 3) = 0 Then
                retmsg = "No"
            Else
                retmsg = "Yes"
            End If
        End If
    End If
    DoStuffIfNotEmpty = retmsg

End Function

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