根据单元格值

时间:2016-12-11 12:31:36

标签: excel vba excel-vba

我尝试搜索网络和Stack;但是,我找不到任何有用的东西。我正在尝试创建一个非常简单的事件,当单元格值不包含非法字符时,将重命名工作表。

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

Target = Sh.Cells(1, 1)
If InStr(Target, "\") > 0 Or IsEmpty(Target) = True _
    Or InStr(Target, "/") > 0 Or InStr(Target, "*") > 0 _
    Or InStr(Target, "[") > 0 Or InStr(Target, "]") > 0 _
    Or InStr(Target, ":") > 0 Or InStr(Target, "?") > 0 Then
Else
    Sh.Name = Target
End If

End Sub

它应该像这样工作:如果A1中的值包含所有合法字符,请重命名工作表。这确实发生了,但它也改变了我对任何其他单元格赋予工作表名称的任何值。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

尝试一下:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim ws As Worksheet, r As Range, s As String

    Set ws = Target.Parent
    Set r = Intersect(Target, ws.Range("A1"))

    If r Is Nothing Then Exit Sub

    s = r.Value
    If InStr(s, "\") > 0 Or s = "" _
        Or InStr(s, "/") > 0 Or InStr(s, "*") > 0 _
        Or InStr(s, "[") > 0 Or InStr(s, "]") > 0 _
        Or InStr(s, ":") > 0 Or InStr(s, "?") > 0 Then
    Else
        Sh.Name = s
    End If
End Sub

注:

代码不会检查是否重复使用值。

答案 1 :(得分:1)

我更喜欢下面的方法,因为您可以预定义无效字符列表,而无需在If..End If块中对其进行硬编码:

Option Explicit

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

    Dim rngA1OfSheet As Range
    Dim varInvalidChars As Variant
    Dim varTest As Variant
    Dim blnCheck1 As Boolean
    Dim blnCheck2 As Boolean

    Set rngA1OfSheet = Sh.Range("A1")

    If Not Intersect(Target, rngA1OfSheet) Is Nothing Then
        blnCheck1 = IsEmpty(rngA1OfSheet.Value)

        varInvalidChars = Array("\", "/", "*", "[", "]", ":", "?")
        blnCheck2 = False
        For Each varTest In varInvalidChars
            If InStr(1, rngA1OfSheet.Value, CStr(varTest), vbTextCompare) > 0 Then
                blnCheck2 = True
                Exit For
            End If
        Next

        If Not blnCheck1 And Not blnCheck2 Then
            Sh.Name = rngA1OfSheet.Value
        End If

    End If


End Sub