如何检查excel列中的依赖关系,并显示excel-vba中的错误?

我在我的excel中有一系列的列。 为了简单起见,我们可以考虑马铃薯,番茄,货币1,金额1,货币2,金额2 …货币10,金额10

如果Currency1或Amount1为空; 那么它应该用红色填充这两个单元格; 它应该忽略这些单元格。

我已经尝试了以下的事情。 然而,它不适合我的情况,我不得不包括很多迭代。 请尽可能提出更好的方法。

我的代码如下:

' Function to get last column cols = LastColumnInOneRow() ' Function to get last row Rows = fnLastRowOfAColumn(cols) For num_cols = 1 To cols For num_rows = 2 To Rows cell_value = Cells(num_rows, num_cols) Set selected_attr = Cells(1, num_cols) Select Case selected_attr Case Is = "Currency1" If Cells(num_rows + 1, num_cols) <> "" Then Cells(num_rows, num_cols).Interior.ColorIndex = 0 Else Cells(num_rows, num_cols).Interior.ColorIndex = 3 End If Case Is = "Amount1" If Cells(num_rows - 1, num_cols) <> "" Then Cells(num_rows, num_cols).Interior.ColorIndex = 0 Else Cells(num_rows, num_cols).Interior.ColorIndex = 3 End If ' Till end of sheet ... End Select Next num_rows '+ 1 Next num_cols '+ 1 

对不起,我不能评论,但我可以给你以下提示:

您最终可以将条件格式设置为vba代码,下面是将范围设置为红色(如果不为空)作为条件格式的示例:

 Range("A2", Cells(Rows, Cols)).FormatConditions.Delete 'this would eventually delete previous formating With Range("A2", Cells(Rows, Cols)).FormatConditions.Add(xlCellValue, xlNotEqual, "=" & Chr(34) & Chr(34)) .Interior.ColorIndex = 3 End With 

编辑:这里是一个例子,如果您的单元格等于“Currency1”,并且单元格波纹pipe作为条件格式为空,则将范围设置为绿色:

 With Range("A2", Cells(Rows, Cols)).FormatConditions.Add(xlExpression, , "= AND(A3<>" & Chr(34) & Chr(34) & "; A2=" & Chr(34) & "Currency1" & Chr(34) & ")") .Interior.ColorIndex = 4 End With 

我在金额1,金额2中使用以下方法解决了我的情况。金额10:

  If IsEmpty(Cells(num_rows, num_cols + 1)) = True And IsEmpty(Cells(num_rows, num_cols)) = True Then If .Test(cell_value) = False Then Cells(num_rows, num_cols).Interior.ColorIndex = 3 Else Cells(num_rows, num_cols).Interior.ColorIndex = 0 End If Set RegEx = Nothing End With ElseIf (IsEmpty(Cells(num_rows, num_cols + 1)) = False And IsEmpty(Cells(num_rows, num_cols)) = True) Then Cells(num_rows, num_cols).Interior.ColorIndex = 3 Cells(num_rows, num_cols + 1).Interior.ColorIndex = 0 ElseIf (IsEmpty(Cells(num_rows, num_cols + 1)) = True And IsEmpty(Cells(num_rows, num_cols)) = False) Then Cells(num_rows, num_cols + 1).Interior.ColorIndex = 3 Cells(num_rows, num_cols).Interior.ColorIndex = 0 Else Cells(num_rows, num_cols).Interior.ColorIndex = 0 Cells(num_rows, num_cols + 1).Interior.ColorIndex = 0 End If