根据相邻单元格中的值填充单元格

时间:2019-11-15 19:59:50

标签: excel vba

我有这个工作的宏按钮,可以将B2:B15范围内的“所有状态”“重置”为默认提示,以供同事指示作业的状态:

screenshot

Private Sub CommandButton1_Click()

    Sheets("Sheet1").Range("B2:B15").Value = "please enter status"

End Sub

如果相邻的A列中没有值,我希望此宏停止在B列中填充值“请输入状态”。看屏幕截图,它将使B6:B15为空。 A列的值是vlookup结果。如果没有结果,则vlookup返回零(当前在条件格式的帮助下以白色字体隐藏)

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

也许是这样的:

Private Sub CommandButton1_Click()
    Dim rng as Range
    Set rng = Sheets("Sheet1").Range("A2:A15")

    If Application.CountA(rng) > 0 Then
        rng.SpecialCells(xlCellTypeConstants).Offset(,1).Value = "please enter status"
    End If
End Sub

编辑

如果列中的单元格是公式,则将xlCellTypeConstants更改为xlCellTypeFormulas

编辑2

这是执行所需操作的简单方法:

Private Sub CommandButton1_Click()
    Dim rng As Range
    Set rng = Sheets("Sheet1").Range("B2:B15")

    rng.Formula = "=IF(A2<>0,""please enter status"", """")"
    rng.Value = rng.Value
End Sub

或使用Evaluate

Private Sub CommandButton1_Click()
    Dim ws As Worksheet
    Set ws = Sheets("Sheet1")

    Dim rng As Range
    Set rng = ws.Range("B2:B15")

    rng.Value = ws.Evaluate("IF(A2:A15<>0,""please enter status"", """")")
End Sub

编辑3 :(第3次是魅力吗?)

另一种选择是,如果找不到工作编号,则Vlookup返回一个空白字符串""而不是0

然后您可以利用Range.SpecialCells的第二个参数,就像这样(由@JvdV提议):

Private Sub CommandButton1_Click()
    Dim rng As Range
    Set rng = Sheets("Sheet1").Range("A2:A15")

    rng.SpecialCells(xlCellTypeFormulas, xlNumbers).Offset(, 1).Value = "please enter status"
End Sub

编辑4

您还可以使用AutoFilter

Private Sub CommandButton1_Click()
    With Sheets("Sheet1").Range("A1:B15")
        .AutoFilter 1, ">0"
            If .Cells.SpecialCells(12).Count > 2 Then .Offset(1).Resize(14, 2).Columns(2).Value = "Please enter status"
        .AutoFilter
    End With
End Sub