在多个工作表中粘贴工作表名称

时间:2015-12-15 15:55:47

标签: excel vba excel-vba

我有一本包含50多个工作表的工作簿。我想将每个工作表的名称复制到该特定工作簿的单元格中。我可以使用带有以下VBA代码的宏一次为一张表执行此操作:

Range("B1") = ActiveSheet.Name

但是当我尝试一次将宏应用于多个工作表时,它就失败了。我希望它只获得前30个工作表的名称。

4 个答案:

答案 0 :(得分:2)

避免依赖ActiveSheet property来标识您要处理的工作表。 With ... End With statement可以轻松提供工作表并帮助检索工作表.Name property

Sub name_Worksheets()
    Dim w As Long

    For w = 1 To 30
        With Worksheets(w)
            .Cells(1, 2) = .Name
        End With
    Next w
End Sub

有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros

答案 1 :(得分:2)

我的理解是你要1)浏览工作簿的前30页和2)将工作表名称粘贴到单元格B1中。

Sub PasteSheetNameInB1()

    For i = 1 To 30 '(1 to 30 because you said " I would like it to get the names of the first 30 worksheets only.")
        ActiveWorkbook.Sheets(i).Select 'Iterates through first 30 sheets
        Range("B1") = ActiveSheet.Name 'Pastes Sheet name into B1
    Next i


End Sub

答案 2 :(得分:1)

您可以使用此代码:

For i = 1 To 30
 Sheets(i).Range("B1").Formula = "=MID(CELL(""filename"",A1),FIND(""]"",CELL(""filename"",A1))+1,255)"
Next

现在,如果您更改任何工作表的名称,您不需要再次运行宏,Rnage中的公式(" B1")将显示新名称。

答案 3 :(得分:0)

因此,使用此代码,您将粘贴到目标工作簿中,
你只需要改变:

  1. workbook_to_scan's Name
  2. Sheet's name in which to paste the names
  3. 满足您的需求!

    Sub test_johnB()
    Dim wB1 As Workbook, _
        wB2 As Workbook, _
        wSDest As Worksheet, _
        wS As Worksheet, _
        i As Integer
    
    Set wB1 = ThisWorkbook
    Set wB2 = Workbooks("workbook_to_scan's Name")
    Set wSDest = wB1.Sheets("Sheet's name in which to paste the names")
    
    i = 0
    For Each wS In wB2.Sheets
       wSDest.Range("B1").Offset(i, 0) = wS.Name
    Next wS
    
    End Sub