我们有一本工作簿,需要每个月更改工作表的名称,我决定为其他员工自动化它。因此,经过一些研究,我发现最好的方法是引用细胞名称。我需要它来开始在第四张纸上运行并运行到倒数第二张纸上。我找到了一些VBA代码并对其进行了编辑,直到到达这一点为止:
Sub RenameSheet()
Dim ShCnt As Integer 'count of sheets in workbook
Dim myarray() As String 'array of new worksheet names
Dim Month() As String 'mystery variable -- not used in this code
Dim i As Integer 'loop counter
Dim Lrow As Integer 'number of new worksheet names.
ThisWorkbook.Sheets("SETUP").Select 'select the sheet that has the list of new names
Lrow = Range("T1").End(xlDown).Row 'get range that contains new worksheet names
ShCnt = ThisWorkbook.Sheets.Count 'get number of worksheets in the workbook
ReDim myarray(1 To Lrow) 'resize array to match the number of new worksheet names
For i = 1 To UBound(myarray) 'loop through array of new sheet names
myarray(i) = Range("T" & i).Value 'insert new sheet name into array
Debug.Print Range("T" & i).Value 'show the new worksheet name in 'the Immediate window to be able to check that we're getting what we want
Next i 'end of loop
For i = 4 To ShCnt - 1 'loop through array of existing worksheets
Sheets(i).Name = myarray(i) 'rename each worksheet with the matching name from myarray
Next i 'end of loop
MsgBox "Sheets name has changed successfully" 'report success
End Sub
我的问题是,我需要第4张表以“ T2”单元格中的值开头。我发现这段代码改变了起点:
For i = 1 To UBound(myarray)
myarray(i) = Range("T" & i).Value
Debug.Print Range("T" & i).Value
Next i
当我换成myarray(i) = Range("T" & i).Value
用myarray(i) = Range("T2" & i).Value
它开始于T24细胞由于某种原因(这可能与我的按钮?安置办)和myarray(i) = Range("T" + 1 & i).Value
不工作。
我也尝试将For i = 1 To UBound(myarray)
to更改为For i = 2 To UBound(myarray)
,但也没有用。
有人可以帮我弄清楚如何获取它,以便使单元格T2中的信息最终出现在第四张纸上并从那里开始吗?提前非常感谢您。
我建议在工作簿中的工作表之间循环,并使用循环计数器来索引T列中的名称范围:
Sub RenameSheet()
Dim ShCnt As Integer
Dim i As Integer
Dim ws_setup As Worksheet
Set ws_setup = ThisWorkbook.Worksheets("SETUP")
ShCnt = ThisWorkbook.Worksheets.Count
Const start_ws_index = 4
For i = start_ws_index To ShCnt - 1
ThisWorkbook.Worksheets(i).Name = _
ws_setup.Range("t2").Offset(i - start_ws_index, 0).Value
Next i
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句