2014-02-26 27 views
0

在Excel 2007的特定小區,我試圖完成通過VBA代碼如下:設置單元格值Null當用戶選擇在列

  1. 在山口-A,如果該值是AA, bb,cc,則Col-E中的值應分別更新爲100,1000,10000。

  2. 如果Col-E中的值爲10000,則單元格中的字體顏色應爲灰色。 (下面VBA代碼在步驟執行的細節 - 1,2)

這裏是我觸擊:

一個。在Col-A中,用戶選擇值「cc」,行中的Col-E更新爲「10000」,字體灰顯。

b。當用戶選擇具有「10000」的Col-E中的單元時,則應該清除特定單元中的內容。如果用戶輸入任何值,則應保留用戶輸入的值。否則,如果用戶不輸入任何值,並導航到另一個單元格,然後在「10000」和字體將變灰應該出現

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 
    Dim LastRow As Long  
    Dim i As Long 

    LastRow = Range("A" & Rows.Count).End(xlUp).Row 

    For i = 2 To LastRow 
     If Range("A" & i).Value = "aa" Then 
     Range("E" & i).Value = "100" 
     ActiveSheet.Range("E" & i).Font.Color = RGB(0, 0, 0) 
     End If 
    Next i 

    For i = 2 To LastRow 
     If Range("A" & i).Value = "bb" Then 
     Range("E" & i).Value = "1000" 
     ActiveSheet.Range("E" & i).Font.Color = RGB(0, 0, 0) 
     End If 
    Next i 

    For i = 2 To LastRow 
     If Range("A" & i).Value = "cc" Then 
     Range("E" & i).Value = "10000" 
     ActiveSheet.Range("E" & i).Font.Color = RGB(191, 191, 191) 
     End If 
    Next i  
End Sub 

回答

0

我認爲你需要提供一些更多的信息和方向比練成到目前爲止你所做的一切。爲了實現您的目標,我在腳本中添加了一些額外的行,它適用於我。

Dim LastRow As Long 
     Dim i As Long 

     LastRow = Range("A" & Rows.Count).End(xlUp).Row 

     Dim blnUserActive As Boolean 
     blnUserActive = False 
     Dim rngActive As Range 
     Set rngActive = Range("E2:E" & LastRow) 
     If Not (Application.Intersect(rngActive, Target) Is Nothing) And Target.Value = "10000" Then 
      'user has clicked in Column E and the value there is 10000 
      blnUserActive = True 
      Target.Value = "" 
     End If 

     For i = 2 To LastRow 
      If Range("A" & i).Value = "aa" Then 
       Range("E" & i).Value = "100" 
       ActiveSheet.Range("E" & i).Font.Color = RGB(0, 0, 0) 
      End If 
     Next i 

     For i = 2 To LastRow 
      If Range("A" & i).Value = "bb" Then 
       Range("E" & i).Value = "1000" 
       ActiveSheet.Range("E" & i).Font.Color = RGB(0, 0, 0) 
      End If 
     Next i 


     For i = 2 To LastRow 
      ' the following two lines tells the loop to ignore this step if proven true 
      If Range("E" & i).Value <> "" And Range("E" & i).Value <> "10000" Then GoTo IgnoreEntry 
      If blnUserActive Then GoTo IgnoreEntry 

      If Range("A" & i).Value = "cc" Then 
       Range("E" & i).Value = "10000" 
       ActiveSheet.Range("E" & i).Font.Color = RGB(191, 191, 191) 
      End If 
IgnoreEntry: 
     Next i 

我希望這可以解決您的問題。乾杯。

相關問題