提示用用户定义的文本替换空单元格

时间:2016-10-11 15:26:17

标签: excel vba excel-vba

我需要VBA代码来检查范围内的空白单元格。如果该范围内有任何空白,则应该出现一个框,允许您键入要替换空白的内容。下面的代码实现我想要的,但即使没有任何空白,也会出现提示ALWAYS。我怎么做才能让盒子只出现空白?

Sub ReplaceBlanks()
  Dim Lastrow As Integer
  Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

  Range("D84:D" & Lastrow).Select
  Dim cell As Range
  Dim InputValue As String
  On Error Resume Next
  InputValue = InputBox("Enter value that will fill empty cells in selection", "Fill Empty Cells")
  For Each cell In Selection
    If IsEmpty(cell) Then
      cell.Value = InputValue
    End If
  Next
End Sub

3 个答案:

答案 0 :(得分:3)

Sub ReplaceBlanks()
Dim Lastrow As Integer
Dim srchRng As Range

Lastrow = Cells(Rows.Count, 1).End(xlUp).Row
Set srchRng = Range(Cells(84, 4), Cells(Lastrow, 4))

Dim InputValue As String

If srchRng.Count - WorksheetFunction.CountA(srchRng) > 0 Then
    InputValue = InputBox("Enter value that will fill empty cells in selection", _
                          "Fill Empty Cells")
    srchRng.SpecialCells(xlCellTypeBlanks).Value = InputValue
End If
End Sub

这也会在范围变量中添加,因此您avoid using .Select。它还假设您只需要一个输入值。如果您希望它触发每个空单元格,请将inputValue = ...放在If IsEmpty(cell)循环中。

If a cell is empty循环的替代方案是一行修复:

Range(Cells(84,4),Cells(lastRow,4)).SpecialCells(xlCellTypeBlanks).Value = InputValue。这将占用D84:DlastRow中的所有空格,并填写InputValue所有内容。无需循环。

答案 1 :(得分:1)

Sub ReplaceBlanks()
Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Range("D84:D" & Lastrow).Select
Dim cell As Range
Dim InputValue As String
On Error Resume Next
For Each cell In Selection
If IsEmpty(cell) Then
InputValue = InputBox("Enter value that will fill empty cells in selection", _
"Fill Empty Cells")
cell.Value = InputValue
End If
Next
End Sub

将线移到正确的位置:D

答案 2 :(得分:1)

YourRange.Cells.Count - WorksheetFunction.CountA(YourRange)将为您提供空白计数,以便您检查是否有空白:

Sub ReplaceBlanks()
    Dim Lastrow As Integer
    Lastrow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row 'Use 4 as it is the D column you are working with

    Dim cel As Range 'Use cel as CELL can be confused with functions
    Dim InputValue As String
    If Range("D84:D" & Lastrow).Cells.Count - WorksheetFunction.CountA(Range("D84:D" & Lastrow)) > 0 Then
        InputValue = InputBox("Enter value that will fill empty cells in selection", "Fill Empty Cells")
        For Each cel In Range("D84:D" & Lastrow)
            If IsEmpty(cel) Then
                cel.Value = InputValue
            End If
        Next
    End If
End Sub