简体   繁体   中英

How to rename a worksheet based on a cell value

How can I rename a sheet using based on cell A1 value from sheet 2.
I tried the following code:

    Private Sub CommandButton1_Click()
        Sheet1.Name = Sheet2.Range("A1").Value
    End Sub

but if I use

Sheets(1).Name = Sheets(2).Range("A1").Value

or

Sheets("Sheet1") = Sheets("Sheet2").Range("A1").Value

it works but I need to use code name of the sheets so when I rename sheet 2 the code would still work.

In general I found your question very unclear, but here are the 3 possible interpretations:

  1. Set first Sheet as the [A1] of the 2nd Sheet .

     Private Sub CommandButton1_Click() If Not IsEmpty(Sheets(2).Range("A1")) ThisWorkbook.Sheets(1).Name = ThisWorkbook.Sheets(2).Range("A1") End If End Sub
  2. Set first Sheet as the [A1] of the last Sheet

     Private Sub CommandButton1_Click() If Not IsEmpty(Sheets(Sheets.Count).Range("A1")) ThisWorkbook.Sheets(1).Name = ThisWorkbook.Sheets(Sheets.Count).Range("A1") End If End Sub
  3. Set first Sheet as the [A1] of the Sheet named "Sheet2"

     Private Sub CommandButton1_Click() If Not IsEmpty(Sheets("Sheet2").Range("A1")) ThisWorkbook.Sheets(1).Name = ThisWorkbook.Sheets("Sheet2").Range("A1") End If End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM