提示用用户定义的文本replace空单元格
我需要VBA代码来检查范围内的空白单元格。 如果在该范围内有任何空格,应该出现一个框让您键入要replace的空格。 下面的代码做我想要的,但提示总是出现,即使没有任何空白。 我该如何做,所以只有有空白的时候才会出现这个框。
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
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
这也增加了范围variables,所以你避免使用.Select
。 它还假定您只需要一个input值。 如果您希望触发每个空单元格,请将inputValue = ...
放入If IsEmpty(cell)
循环中。
你的替代schemeIf a cell is empty
循环,是一个单行修正:
Range(Cells(84,4),Cells(lastRow,4)).SpecialCells(xlCellTypeBlanks).Value = InputValue
。 这将采取D84:DlastRow
所有空白,并填写任何InputValue
。 不需要循环。
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
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