使用宏重命名选项卡

时间:2019-06-21 15:38:35

标签: excel vba

我想重命名工作簿中的选项卡,以便在第一个选项卡中的某个单元格中更改图形时,选项卡名称随之自动更改。

我不需要为宏分配按钮(除非有必要)。到目前为止,我的代码尚未完成。 这是我的原始代码,但选项卡名称不会随之改变。

Private Sub Worksheet_Change(ByVal Target As Range)
'calls ChangeSheetName() in a regular code module to do the work
'when the contents of cell B1 on the sheet changes
  If Target.Address <> 1. & "$B$1" _
   Or Target = "" _
   Or Target.Cells.Count > 1 Then
    Exit Sub ' nothing to be done
  End If
 Run "ChangeSheetName" ' call the routine to do the work
End Sub

如果有人可以帮助您,那就太好了!

更新:我已经在下面尝试使用此代码,但是它仍然不会更改选项卡。应该注意的是,用于命名的单元格在另一个选项卡中。

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
If Target.Address(False, False) = " '0. Overview'!$B$3" Then
    On Error Resume Next
    Me.Name = Target.Value
    On Error GoTo 0
End If
End Sub

3 个答案:

答案 0 :(得分:0)

没有太多更改:

Private Sub Worksheet_Change(ByVal Target As Range)

    'calls ChangeSheetName() in a regular code module to do the work
    'when the contents of cell B1 on the sheet changes
    If Target.Address <> "$B$1" Or Target.Value = "" Or Target.Cells.Count > 1 Then
         Exit Sub ' nothing to be done
    End If

    Call ChangeSheetName ' call the routine to do the work

End Sub

但是要补充一点,您可以更改为仅确保Target.Address$B$1,然后运行该呼叫。

Private Sub Worksheet_Change(ByVal Target As Range)

    'calls ChangeSheetName() in a regular code module to do the work
    'when the contents of cell B1 on the sheet changes
    If Target.Address = "$B$1" And Target.Value <> "" Then
         Call ChangeSheetName ' call the routine to do the work
    End if

End Sub

答案 1 :(得分:0)

我假设您想将工作表的名称更改为单元格B1中写的任何内容。在这种情况下,您可以使用这段代码,而不是在每张纸上使用一个代码。

如果范围不在工作表上,则Typenname检查应防止出现任何错误。

在ThisWorkbook的代码中:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Not TypeName(Target.Parent) = "Worksheet" Then Exit Sub
    If Target.Address = "$B$1" And Target.Value2 <> "" Then
        Target.Worksheet.Name = Target.Value2
    End If
End Sub

答案 2 :(得分:0)

这可能会有所帮助,一旦您退出sheet4标签,sheet1,2,3就会更改

Private Sub Worksheet_Deactivate()
    Sheet1.Name = "North " & Sheet4.[E1] & " " & Sheet4.[F1]
    Sheet2.Name = "EAST SIDE " & Sheet4.[E1] & " " & Sheet4.[F1]
    Sheet3.Name = "WEST SIDE " & Sheet4.[E1] & " " & Sheet4.[F1]
End Sub