[英]How to check dependency in excel columns and display error in 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”,並且單元格的下方為空,則將其范圍設置為綠色作為條件格式:
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
我使用Amount1,Amount2 .. Amount10中的以下內容解決了該情況:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.