如何通过与其他单元格比较来检查单元格是否为空白?



我需要比较2列A和B,其中B有公式。

  1. 如果列a末尾有额外的数据,列B中相应的单元格为空,则从上面的行

    复制公式
  2. 如果列a为空,列B有公式,然后删除这些公式!

我们可以使用VBA吗?

你的问题实际上没有详细说明。下面是你想要的最广泛的解释。

Sub Correspond_Columns()
Const stMT$ = "Correspond Columns"
Dim lgR&, lgLastFormulaRow

''' Pocess all rows from 1 down to the last used row
For lgR = 1 To Cells.SpecialCells(xlCellTypeLastCell).Row

''' Get row number of lowest row with a formula in column B
If Cells(lgR, 2).HasFormula Then lgLastFormulaRow = lgR

''' If cell in column A is not empty and there's no formula in corresponding column B:
''' o  If found row with formulas: Copy it to to here
''' o  Otherwise: Report and end
If Cells(lgR, 1) <> "" Then
If Not Cells(lgR, 2).HasFormula Then
If lgLastFormulaRow > 0 Then
Cells(lgLastFormulaRow, 2).Copy
Cells(lgR, 2).PasteSpecial xlPasteFormulas
Else
MsgBox Title:=stMT, Prompt:="Missing formula, but no preceding formula found"
Exit Sub
End If
End If

''' If cell in column A is empty: Clear whatever is in corresponding column B
Else: Cells(lgR, 2).ClearContents
End If
Next lgR
End Sub

只是为了检查一下:这将是非常容易手工完成的,使用控件导航到列的底部,然后双击B中的最后一个公式以沿着a扩展它,或者按下shift键选择B中的剩余公式并删除。但是假设您确实需要使用VBA(也许您有许多这样的文件):

在VBA中,它将是这样的:向下迭代列,检查两个单元格是否为空以结束循环。如果A为空,删除B;如果B是空的,上面复制函数。

假设列A为列1,B为列2:

Sub CheckEmptyColumns()
i = 2
Do Until IsEmpty(Cells(i, 1) AND IsEmpty(Cells(i,2)))
If IsEmpty(Cells(i,1)) Then
'A is empty, B is not: Clear B
Cells(i,2).Clear
ElseIf IsEmpty(Cells(i,2)) Then
'B is empty, A is not: copy formula
Cells(i,2).FormulaR1C1 = Cells(i-1,2).FormulaR1C1
i = i + 1
Loop
End Sub

编辑:如果公式使用相对单元格,则使用单元格。用FormulaR1C1代替cell。公式——感谢Spinner的提示。