简体   繁体   中英

Macro for adding a worksheet name to a cell

First post here, and still quite a newbie at macros :-)

Is there any way that I can use a macro to insert a newly created sheet name into a cell?

I am creating a workbook for the different suppliers that we buy from.

I have a macro (from another helpful post on this forum :-)) which copies and then provides a prompt to input the supplier's name; this name is then given as the worksheet name.

I've tried to find the command to take that worksheet name and populate it into cell B1 - is it possible to do this?

My current macro is:

Sub New_Page()
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = wb.Sheets("Supplier")
    Dim newws As Worksheet, sh As Worksheet, newname
    Dim query As Long, xst As Boolean, info As String

    retry:
    xst = False
    newname = Application.InputBox("Enter the Supplier's name.", info, , , , , , 2)
    If newname = "False" Then Exit Sub
    For Each sh In wb.Sheets
        If sh.Name = newname Then
            xst = True: Exit For
        End If
    Next
    If Len(newname) = 0 Or xst = True Then
        info = "Sheet name is invalid. Please retry."
        GoTo retry
    End If
    ws.Copy after:=ws: Set newws = ActiveSheet: newws.Name = newname
End Sub

Thank you for your help!

Following your coding style, you can find the active command at the end of this line.

ws.Copy after:=ws: Set newws = ActiveSheet: newws.Name = newname: newws.Range("B1") = newws.Name

Given that you seem to be creating new worksheets based on a supplier's name, you might find Can I sort by worksheet tabs interesting.

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