2015-10-06 51 views
0

下面是運行的,但我只想要這個有效的,例如B10到H13在表一。有沒有簡單的方法來選擇vba的範圍? 通常Excel提供一個範圍按鈕,但在這種情況下我不相信。有效的vba範圍

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) 
     Cancel = True 
    Worksheet_SelectionChange Target 

End Sub 
Private Sub Worksheet_SelectionChange(ByVal Target As Range) 
    'If the target cell is clear 
    If Target.Interior.ColorIndex = xlNone Then 

     'Then change the background to the specified color 
     Target.Interior.ColorIndex = 4 

     'But if the target cell is already the specified color 
     ElseIf Target.Interior.ColorIndex = 4 Then 

     'Then change the background to the specified color 
     Target.Interior.ColorIndex = 3 

     'But if the target cell is already the specified color 
     ElseIf Target.Interior.ColorIndex = 3 Then 

     'Then clear the background color 
     Target.Interior.ColorIndex = xlNone 

    End If 
End Sub 
+0

我發現它有助於記錄一個宏,而手動做我想做的代碼。然後看看宏代碼,看看如何完成任務。 – Crowcoder

+1

嘗試使用谷歌搜索「只運行特定範圍的宏」,看看是否讓你走向正確的方向... – sous2817

+0

我不知道我是否誤解了一些東西。如果您想在範圍B10:H13而不是活動選項上運行您的代碼,請將範圍(「B10:H13」)替換爲「目標」。 – Dorian

回答

0

已編輯...不確定這是不是你想要的,但它應該給你一個好的開始。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) 
     Cancel = True 
    Worksheet_SelectionChange Target 

End Sub 
Private Sub Worksheet_SelectionChange(ByVal Target As Range) 
    'If the target cell is within the range 
    If Not Application.Intersect(Target, Range("B10:H13")) Is Nothing Then 

     'If the target cell is clear 
     If Target.Interior.ColorIndex = xlNone Then 

      'Then change the background to the specified color 
      Target.Interior.ColorIndex = 4 

      'But if the target cell is already the specified color 
      ElseIf Target.Interior.ColorIndex = 4 Then 

      'Then change the background to the specified color 
      Target.Interior.ColorIndex = 3 

      'But if the target cell is already the specified color 
      ElseIf Target.Interior.ColorIndex = 3 Then 

      'Then clear the background color 
      Target.Interior.ColorIndex = xlNone 

     End If 
    End If 
End Sub 
+0

我不是很確定在哪裏插入它......我不習慣使用vba的。 –

+0

太棒了!這正是我所期待的! –

0

不知道這是你想要的,但如果目標不是B10裏面,你可以退出用下面的代碼子:H13範圍:

If Intersect(Target, Range("B10:H13")) Is Nothing Then Exit Sub 
+0

另外,是否可以在同一行內添加更多的單元格。如果我想要B10:H13和G13:V14等? –

+0

你可以使用'Range(「B10:H13,G13:V14」)''。您還可以使用聯合()擴展範圍 –

+0

絕對精彩! –