1

我正在使用以下方法命名工作表:

            arrayCollabName = Array("CBDeltaBlockStatus_SAP03_to_Delta01", "CBDeltaBlockStatus_SAP03_to_Delta02", "CBDeltaDeliveryInformation_SAP03_to_Delta01") 

            If Len(arrayCollabName(idx)) > 31 Then
                 ActiveSheet.Name = Left(arrayCollabName(idx), 31)
            Else
                 ActiveSheet.Name = arrayCollabName(idx)
            End If

在数组中,当名称被截断为 31 个字符并且 VB 抛出错误“无法将工作表重命名为与另一个工作表、引用的对象库或由 visualbasic 引用的工作簿相同的名称”时,数组中的第一个和第二个名称相似。

任何方式我都可以做到这一点而不会出错,并将工作表命名为CBDeltaBlock_SAP03_to_Delta01CBDeltaBlock_SAP03_to_Delta02或任何所需的名称。

4

1 回答 1

0

这是一个更改工作表名称(如果已存在)的示例。

Option Explicit

Sub Sample()
    Dim i As Long
    Dim strShName As String

    strShName = "BlahBlah"

    Sheets.Add

    Do Until DoesSheetExist(strShName) = False
        i = Int((1000 * Rnd) + 1)
        strShName = strShName & i
    Loop

    ActiveSheet.Name = strShName
End Sub

Function DoesSheetExist(ByVal strSheetName As String) As Boolean
    Dim ws As Worksheet
    On Error Resume Next
    Set ws = Sheets(strSheetName)
    On Error GoTo 0
    If Not ws Is Nothing Then DoesSheetExist = True
End Function

上述方法将在工作表末尾添加一个随机数。如果您想按升序排列,请使用以下代码。

Option Explicit

Sub Sample()
    Dim i As Long
    Dim strShName As String

    strShName = "BlahBlah"

    Sheets.Add

    If DoesSheetExist(strShName) = True Then
        i = 1
        Do Until DoesSheetExist(strShName & i) = False
            i = i + 1
        Loop
        strShName = strShName & i
    End If

    ActiveSheet.Name = strShName
End Sub

Function DoesSheetExist(ByVal strSheetName As String) As Boolean
    Dim ws As Worksheet
    On Error Resume Next
    Set ws = Sheets(strSheetName)
    On Error GoTo 0
    If Not ws Is Nothing Then DoesSheetExist = True
End Function

注意:上面的代码只是示例代码。错误处理并没有包含在上面的代码中,不用说错误处理是必须的:)

于 2012-04-26T16:21:10.803 回答