如何让VBA代码在多张表格上运行?

时间:2017-09-07 22:49:53

标签: excel vba excel-vba

我想知道如何让这段代码适用于将在Excel工作簿中制作的每张工作表和新工作表。新表谢谢所有帮助的人。

  Dim cmt As Comment
  Dim charCount As String
  Dim prevTarget As Range
  Sub Worksheet_C(ByVal Target As Range)
    If Target.Value <> Empty Or Target.Value <> "0" Then
            If Target.Value <> Empty Then
            Set prevTarget = Target
            Set Target = Target
            End If
        Set cmt = prevTarget.Comment
            If Target = Empty Then
            Set prevTarget = Target
            End If
            If cmt Is Nothing Then
            'MsgBox "There is no comment"
            ElseIf Len(cmt.Text) > 150 Then
            charCount = Len(cmt.Text)
            MsgBox "Character Limit is 150. Your comment contains " + charCount + "."
            End If
    End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Call Worksheet_C(Target)
End Sub

2 个答案:

答案 0 :(得分:0)

Worksheet_SelectionChange 是一个特定于工作表的例程。

如果手动创建新工作表,则无法轻松控制工作表的VBA内容(除非您运行后台流程来轮询工作表并检查代码是否存在)。

但是,如果工作表是通过代码创建的,则可以添加也将创建工作表特定VBA代码的代码。

答案 1 :(得分:0)

Workbook_SheetSelectionChange()中的 ThisWorkbook 将执行所有工作表:

ThisWorkbook 模块中:

Option Explicit

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    RestrictCommentSize Target
End Sub

Module1 (一个新的通用VBA模块)可以包含您的初始Sub Worksheet_C(清理一下)

Option Explicit

Public Sub RestrictCommentSize(ByVal Target As Range)
    With Target
        If .CountLarge = 1 Then
            If Len(.Value2) <> 0 And .Value2 <> "0" And Not .Comment Is Nothing Then
                If Len(.Comment.Text) > 150 Then
                    Dim msg As String
                    msg = "Your comment contains " & Len(.Comment.Text) & " characters"
                    MsgBox msg & vbCrLf & vbCrLf & "(more than the max of 150)"
                End If
            End If
        End If
    End With
End Sub