简体   繁体   English

Excel宏,用于更改单元格值以匹配工作表的名称

[英]Excel Macro for Changing cell value to match the name of the worksheet

I have around 250 sheets in my Excel workbook. 我的Excel工作簿中大约有250张纸。 I would like to change the value of cell B2 in each of the sheets to match the name of their respective worksheet. 我想在每个工作表中更改单元格B2的值以匹配其各自工作表的名称。

How do I go about doing this using a VBA based code ? 如何使用基于VBA的代码执行此操作?

Try: 尝试:

Option Explicit

Sub Get_Sheets_Name()

    Dim ws As Worksheet

    'Loop all sheets in this workbook
    For Each ws In ThisWorkbook.Worksheets

        With ws
            'Import sheet name in B2
            .Cells(2, 2).Value = ws.Name
        End With

    Next

End Sub

Well, you could automate it little bit further than in accepted answer. 好吧,您可以比接受的答案更自动化。

Let's consider: if you change any name of worksheet, you'll have the same problem. 让我们考虑一下:如果您更改工作表的任何名称,您将遇到相同的问题。

So if you'd enter formula in cell B2 to retrieve sheet name, changing name of a worksheet would automatically update cell content as well, opposite to given answer, where you'd need to run the code again and again. 因此,如果您要在单元格B2输入公式以检索工作表名称,则更改工作表的名称也会自动更新单元格内容,这与给定的答案相反,您需要一次又一次地运行代码。

So, consider using such code (once for a lifetime :) ): 因此,请考虑使用此类代码(一生一次:)):

Sub Get_Sheets_Name()
    Dim ws As Worksheet
    'Loop all sheets in this workbook
    For Each ws In ThisWorkbook.Worksheets
        ws.Cells(2, 2).Formula = "=MID(CELL(""filename"",A1),FIND(""]"",CELL(""filename"",A1))+1,256)"
    Next
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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