Automatically change sheet names

2019-08-07 11:06发布

The following code adds/deletes sheets and inserts a list of all the sheet names while making them hyperlinks:

https://stackoverflow.com/a/48159499/9102830

The following code changes the sheet name depending on several cell names:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Target.Address(0, 0) = "C13" Then
    Sh.Name = Sh.Range("B33").Value + "_" + Sh.Range("C13").Value + "_" + Sh.Range("C22").Value + "_N01"
End If
End Sub

The questions are:

  1. Instead of changing when the cell input changes, can this be done automatically?
  2. Could it be a part of the "Sub add_sheet" code? Like, if I add a sheet, it should be named depending on the cells, and since it is copied and the cells are the same, the name will obviously be taken, in which case the name should be "N02" instead of "N01" (instead of the default "(2)" that Excel does).
  3. Finally, when/if the cells are changed, so that the sheet name is not equal to a previous sheet name, could it automatically go back to "N01"?

Thanks in advance!

1条回答
混吃等死
2楼-- · 2019-08-07 11:51

There are a few ways you can handle that. One way is to combine Worksheet_Activate with Worksheet_Calculate, and throw in a public variable.

When you first open up your worksheet, you will automatically set the variable, and the variable will set with every change as well.

Option Explicit

Public myVar As Variant

Private Sub Worksheet_Activate()

    'Set the public variable
    myVar = Range("B33").Value

End Sub

Private Sub Worksheet_Calculate()

    If myVar <> Range("B33").Value Then
        sh.Name = ...
        myVar = Range("B33")
    End If

End Sub

You can also set the variable when you open the workbook with Workbook_Open as well. Really just depends on your particular needs.

查看更多
登录 后发表回答