VBA擅长相对单元格内容检查和操作问题

任何人都可以指出我正确的方向来实现以下目标,

我有两列内容,如果有一个内容,那么需要在其相邻的单元格中有内容。

AB 1 | Content1 | Content2 2 | Content1 | Content2 3 | Content1 | Content2 

我目前有一个工作macros

 Dim ws As Worksheet Dim currentCell As Range Set ws = ThisWorkbook.Sheets(stMember) Set currentCell = ws.Range("A1") Do While Not IsEmpty(currentCell) Set nextCell = currentCell.Offset(0, 1) If IsEmpty(nextCell) Then Application.Goto currentCell MsgBox "Cell " + currentCell + " is empty" Exit Sub End If Set currentCell = currentCell.Offset(1, 0) Loop 

但是,列A和列B可以在同一行中有空值,所以我需要将我的脚本更改为类似(这是一个描述不是macros)

如果上校A有内容,而上校B有,好的

如果栏A是空的,栏B是OK

如果上校A有内容,而上校B没有,则不行

  AB 1 | Content1 | Content2 OK 2 | Content1 | Content2 OK 3 | Content1 | Content2 OK 4 | Content1 | Content2 OK 5 | Content1 | Content2 OK 6 | | OK 7 | Content1 | Content2 OK 8 | Content1 | Content2 OK 9 | Content1 | NOT OK 10| Content1 | Content2 OK 

我没有要求实际的脚本,只是一个概述,也许是最好的方法来实现这一点。

非常感谢你。

就像我在评论bove中提到的那样,不需要VBA代码。 您可以使用

 =IF(AND(B1="",A1<>""),"Not Ok","Ok") 

在这里输入图像说明

如果你真的想使用VBA,那么你不需要循环:)我们将结合上面的公式和VBA代码,以便我们不必循环。

 Sub Sample() Dim lastrow As Long '~~> Change this to the relevant sheet name With Sheets("Sheet1") '~~> Find the last row in Col A/B If Application.WorksheetFunction.CountA(.Cells) <> 0 Then lastrow = .Columns("A:B").Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row Else lastrow = 1 End If '~~> Enter the formula in Col C .Range("C1:C" & lastrow).Formula = "=IF(AND(B1="""",A1<>""""),""Not Ok"",""Ok"")" '~~> Convert the formula to values .Range("C1:C" & lastrow).Value = .Range("C1:C" & lastrow).Value End With End Sub 

编辑

从评论后续。 这是你正在尝试?

 Sub Sample() Dim lastrow As Long '~~> Change this to the relevant sheet name With Sheets("Sheet1") '~~> Find the last row in Col A/B If Application.WorksheetFunction.CountA(.Cells) <> 0 Then lastrow = .Columns("A:B").Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row Else lastrow = 1 End If For i = 1 To lastrow If Len(Trim(.Range("A" & i).Value)) <> 0 And _ Len(Trim(.Range("B" & i).Value)) = 0 Then '~~> Display the message and exit MsgBox "Cell " & .Range("B" & i).Address & " is empty" Exit For End If Next i End With End Sub