[英]How to get VBA code to run on Multiple Sheets?
我想知道如何使此代码在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
Worksheet_SelectionChange是特定于工作表的例程。
如果手动创建新工作表,则无法轻松控制工作表的VBA内容(除非运行后台进程以轮询工作表并检查代码是否存在)。
但是,如果工作表是通过代码创建的,则可以添加代码,这些代码也将创建工作表特定的VBA代码。
ThisWorkbook
的Workbook_SheetSelectionChange()
将对所有工作表执行:
在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.