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

时间:2014-02-26 09:03:45

标签: excel excel-vba vba

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

  1. 在Col-A中,如果值为aa,bb,cc,则Col-E中的值应分别更新为100,1000,10000。

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

  3. 这是我来袭的地方:

    一个。在Col-A中,用户选择值" cc",Col-E在行更新为" 10000"并且字体是灰色的。

    湾当用户选择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
    

1 个答案:

答案 0 :(得分: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

我希望这能解决你的问题。欢呼声。

相关问题