Excel VBA宏:从选择中搜索空白

时间:2016-02-09 21:56:13

标签: excel vba excel-vba

我正在尝试搜索表中的选择,找到一个值,然后返回一个特定的结果。

我正在尝试的条件是:

  1. IF'Name'=空白,返回“N / A”。
  2. 如果'结果'=空白,或“不适用”,则返回“N / A”。
  3. 如果'Count'= 0,则返回“No”,ELSE“Yes”。
  4. 到目前为止我尝试过的代码如下:

    Sub DoStuffIfNotEmpty()
    
      Set M = Selection
    
      If Not IsEmpty(M) Then
         MsgBox "I'm not empty!"
    
      Else
         MsgBox "Empty Value"
    
      End If
    
    End Sub
    

    同样供参考,这是我创建的测试表:

    Reference Image

1 个答案:

答案 0 :(得分:0)

Test()设置要检查的工作表和单元格 - 如果要在此处完成单元格列表的工作 - 并调用DoStuffIfNotEmpty,它会检查名称,结果和按顺序计数列。它甚至没有优雅,但你去... ...

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