Excel宏没有做任何事情?

时间:2011-07-22 17:21:50

标签: excel excel-vba vba

这是我的第一个excel宏(并且第一次使用VBScript),所以它很可能是错误的,但我正在尝试浏览工作簿中的每个工作表,并将工作表重命名为工作表的值“ A2“细胞的价值。顾名思义,当我运行它时,该功能没有做任何事情。然而它正在运行。这是我的代码:

Sub RenameSheets()

   Dim WS_Count As Integer
   Dim I As Integer

   ' Set WS_Count equal to the number of worksheets in the active
   ' workbook.
   WS_Count = ActiveWorkbook.Worksheets.Count

   ' Begin the loop.
   For I = 1 To WS_Count

      ActiveSheet.Name = ActiveSheet.Range("A2").Value

   Next I

End Sub

2 个答案:

答案 0 :(得分:4)

Sub RenameSheets()

Dim WS_Count As Integer
Dim I As Integer

WS_Count = ActiveWorkbook.Worksheets.Count

For I = 1 To WS_Count
Dim WS As Worksheet
Set WS = ActiveWorkbook.Worksheets(I)

'Worksheet names can not be null
If Len(WS.Cells(2, 1)) > 0 Then

    WS.Name = WS.Cells(2, 1)

End If

Next I

End Sub

答案 1 :(得分:3)

您没有选择不同的工作表,因此ActiveSheet不会更改。您可以在下面重写您的函数以获得预期的结果:

Dim currentWorksheet as Worksheet
For Each currentWorksheet in ActiveWorkbook.Worksheets
  currentWorksheet.name = currentWorksheet.Range("A2").Value
Next currentWorksheet

上面是一个for..each循环,它将currentWorksheet设置为工作簿中所有工作表中的每个工作表。