根据单元格值更改范围

时间:2019-11-20 14:30:26

标签: excel vba

下面的代码突出显示单击按钮时留空的单元格。我需要myCellRange有所不同,具体取决于单元格B19是“打开”还是“关闭”。

有人可以指出我的正确方向吗?

Sub AreYouSure()

Dim myCellRange As Range

'identify cell range you work with
Set myCellRange = ThisWorkbook.Worksheets("Input").Range("B5:B21,B23:B26")

'check if number of non-empty cells in range is less than total number of cells in range.
'Depending on result, display message box indicating whether cell range contains any empty
'cell (True) or not (False)

If WorksheetFunction.CountA(myCellRange) < myCellRange.Count Then

    myCellRange.SpecialCells(xlCellTypeBlanks).Interior.ColorIndex = 3

    MsgBox "Please Enter Data In Red Cells And Then Update."

    Exit Sub

End If

Call UpdateRecords

End Sub

2 个答案:

答案 0 :(得分:1)

不确定未指定的内容,只需要遵循以下几行If子句:

Sub AreYouSure()

Dim myCellRange As Range

With ThisWorkbook.Worksheets("Input")
    If .Range("B19").Value = "Closed" Then  'assuming it's B19 on the same sheet ...
        Set myCellRange = .Range("B5:B21,B23:B26")
        If WorksheetFunction.CountA(myCellRange) < myCellRange.Count Then
            myCellRange.SpecialCells(xlCellTypeBlanks).Interior.ColorIndex = 3
            MsgBox "Please Enter Data In Red Cells And Then Update."
            Exit Sub
        End If
    ElseIf .Range("B19").Value = "Open" Then
        'Set myCellRange = ...
        'whatever
    End If
End With

Call UpdateRecords

End Sub

答案 1 :(得分:1)

Sub AreYouSure()

  Dim myCellRange As Range

'identify cell range you work with
If Thisworkbook.Worksheets("Input").Range("B19") = "Open" then
   Set myCellRange = ThisWorkbook.Worksheets("Input").Range("B5:B17,B20:B24")   
Else
   Set myCellRange = ThisWorkbook.Worksheets("Input").Range("B5:B21,B23:B26")
End If

'check if number of non-empty cells in range is less than total number of cells in range. Depending on result, display message box indicating whether cell range contains any empty cell (True) or not (False)
If WorksheetFunction.CountA(myCellRange) < myCellRange.Count Then

myCellRange.SpecialCells(xlCellTypeBlanks).Interior.ColorIndex = 3

    MsgBox "Please Enter Data In Red Cells And Then Update."

  Exit Sub

 End If

  Call UpdateRecords

 End Sub