2017-09-05 38 views
0

我用我的代碼爲auto,每次編輯單元格的內容添加註釋更改註釋。
我想申請的範圍B2代碼:E1000,但我的代碼適用於所有細胞。
那麼如何設置範圍?提前致謝。Excel的VBA設定範圍,以每次加

Private Sub Worksheet_Change(ByVal Target As Range) 
Dim c As Range 
Dim ws As Worksheet 
ActiveSheet.Cells.RowHeight = 25 

For Each c In Target 
    If c.Comment Is Nothing And c.Value <> "" Then 
     With c.AddComment 
      .Visible = False 
      .Text Application.UserName & "-" & Date & " " & c.Value 
      .Shape.TextFrame.AutoSize = True 
     End With 
    ElseIf Not c.Comment Is Nothing And c.Value <> "" Then 
     c.Comment.Text Application.UserName & "-" & Date & " " & c.Value & vbNewLine & c.Comment.Text 
    End If 
Next 
End sub 

回答

0

您可以使用相交聲明此:

Set isect = Application.Intersect(Range("B2:E1000"), Target) 

您的代碼將在這個樣子的:

Private Sub Worksheet_Change(ByVal Target As Range) 
Dim c As Range 
Dim ws As Worksheet 
ActiveSheet.Cells.RowHeight = 25 

Set isect = Application.Intersect(Range("B2:E1000"), Target) 

If Not isect Is Nothing Then 
For Each c In Target 
    If c.Comment Is Nothing And c.Value <> "" Then 
     With c.AddComment 
      .Visible = False 
      .Text Application.UserName & "-" & Date & " " & c.Value 
      .Shape.TextFrame.AutoSize = True 
     End With 
    ElseIf Not c.Comment Is Nothing And c.Value <> "" Then 
     c.Comment.Text Application.UserName & "-" & Date & " " & c.Value & vbNewLine & c.Comment.Text 
    End If 
Next 
end if 
End sub 
1

使用交集功能N,更新​​後的代碼:

Private Sub Worksheet_Change(ByVal Target As Range) 
     Dim c As Range 
     Dim ws As Worksheet 
     dim rng As Range 

     Set rng = Range("B2:E1000") 

     If Intersect(Target, rng) Is Nothing Then Exit Sub 

     ActiveSheet.Cells.RowHeight = 25 

     For Each c In Target 
      If c.Comment Is Nothing And c.Value <> "" Then 
       With c.AddComment 
        .Visible = False 
        .Text Application.UserName & "-" & Date & " " & c.Value 
        .Shape.TextFrame.AutoSize = True 
       End With 
      ElseIf Not c.Comment Is Nothing And c.Value <> "" Then 
       c.Comment.Text Application.UserName & "-" & Date & " " & c.Value & vbNewLine & c.Comment.Text 
      End If 
     Next 
    End sub 
+0

如果不相交(目標,rng)沒有任何結果然後退出子需要刪除「不」,如果適用於上述範圍。 – Ryan

+0

親愛的mohagali,非常感謝! – Ryan

+0

我也是,謝謝 – mohagali