簡體   English   中英

使用Visual Basic格式化Excel單元格

[英]Excel Cells Formatting with Visual Basic

我只是試圖將Excel文件的一些Visual Basic行放在一起,以便當特定列的單元格的內容滿足特定的比較條件時,相應行的顏色將采用預定義的顏色。 這是一些測試代碼:

Private Sub Worksheet_Activate()
  If ActiveCell = "OK" Then
    Range("A13:E13").Select
    With Selection.Interior
     .ColorIndex = 4
     .Pattern = xlSolid
   End With
End If
End Sub

顯然,這必須對所有工作表都起作用,而不僅僅是對13個表起作用。另外,問題是上述方法不適用於ActiveCell 有沒有更有效的方法可以嘗試? 請幫忙!

更換它;

 If ActiveCell = "OK" Then

有了這個;

 If ActiveCell.value = "OK" Then

首先,如果確實不需要,請嘗試避免selectactive* 大多數時候都可以避免使用它們,從而降低了代碼速度。 因此,而不是Range("A13:E13").Select通過“ selection.interior”進行選擇,然后Range("A13:E13").Select “ Range(“ A13:E13”)。Interior”。

您要檢查單元格的值。 因此,它不僅是activecell,也是“ activecell.value”。 甚至更好的“工作表(x)。單元格(y,z).value”或“工作表(x).range(“ yz”)。value”

這是我的答案...

Private Sub Worksheet_Activate()
  If ActiveCell.Value = "OK" Then
     'Here ActiveCell is any cell that is active,
     'but you say, that you want to test the cells of
     'a particular column, in that case you could use
     'Opt 01:
     'If ActiveCell.Column = 1 Then 'Here you are asking for the column
                                    'for the ActiveCell
                                    ' use a nested if
     'If ActiveCell.Value = "OK" Then ' here if the activecell is in the
                                      ' right column and is with the right
                                      'value, you get the rows colored
    'Range("A13:E13").Select 'Well you are using this... but you say
                             'that you want to color the row of the corresponding cell
                             'in that case you can use this:
    Dim r
    Dim rng As Range

    r = ActiveCell.Row
    Set rng = Range(Cells(r, 1), Cells(r, 20)) 'you store inside rng the cells:
                                               'from column 1 = A, Row x
                                               'to column 20 = T, row x
                                               ' where x is the row of the activecell
                                               'you can change the column as you need
    With rng.Interior 'here you can use rng instead selection
                      'and you affect the cells without selecting them.
     .ColorIndex = 4
     .Pattern = xlSolid
   End With
End If
End Sub

或者您可以使用條件格式...

在其中評估所需的列單元格的內容。 我認為這是您所說的一種更好的方式。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM