Excel 当用户选择列中的特定单元格时,将单元格值设置为Null

Excel 当用户选择列中的特定单元格时,将单元格值设置为Null,excel,vba,Excel,Vba,在Excel 2007中,我试图通过VBA代码完成以下工作: 在A列中,如果值为aa、bb、cc,则E列中的值应分别更新为100、1000、10000 如果Col-E中的值为10000,则单元格中的字体颜色应变灰。下面的VBA代码正在执行步骤-1、2中的详细信息 这是我震惊的地方: a。在A列中,用户选择值cc,行中的E列更新为10000,字体变灰 b。当用户选择Col-E中有10000个单元格时,应清除特定单元格中的内容。如果用户输入任何值,则应保留用户输入的值。否则,如果用户未输入任何值并导

在Excel 2007中,我试图通过VBA代码完成以下工作:

在A列中,如果值为aa、bb、cc,则E列中的值应分别更新为100、1000、10000

如果Col-E中的值为10000,则单元格中的字体颜色应变灰。下面的VBA代码正在执行步骤-1、2中的详细信息

这是我震惊的地方:

a。在A列中,用户选择值cc,行中的E列更新为10000,字体变灰

b。当用户选择Col-E中有10000个单元格时,应清除特定单元格中的内容。如果用户输入任何值,则应保留用户输入的值。否则,如果用户未输入任何值并导航到另一个单元格,则应显示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

我认为您需要为excel提供比您目前所做的更多的信息和指导。为了实现你的目标,我在你的脚本中添加了一些额外的行,这对我很有用

    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
我希望这能解决你的问题。干杯