首页 > 解决方案 > 使用列表中的名称创建新工作表

问题描述

我对 VBA 很陌生,我的代码有问题。我有不同的酒店名称,从 B4 到 B27。我的目标是创建新的工作表并用酒店名称命名每个工作表(从列表中向下)。我尝试运行下面的子过程,但出现错误。错误说:

“运行时错误‘1004’:应用程序定义的或对象定义的错误”

它指的是我的评论下方的行。关于为什么会发生这种情况以及如何解决这个问题的任何想法?

Sub sheetnamefromlist()

Dim count, i As Integer

count = WorksheetFunction.CountA(Range("B4", Range("B4").End(xlDown)))

i = 4

Do While i <= count

' next line errors
Sheets.Add(after:=Sheets(Sheets.count)).Name = Sheets("LocalList").Cells(i, 2).Text

i = i + 1

Loop

Sheets("LocalList").Activate

End Sub

标签: excelvba

解决方案


这是我快速写的东西

一些事情

  1. 不要像那样找到最后一行。你可能想看这个
  2. 不要.Text用来读取单元格的值。您可能想了解.text、.value 和 .value2 之间的区别是什么?
  3. 在尝试创建其他工作表之前检查工作表是否存在,您将收到错误消息。

这是你正在尝试的吗?

Option Explicit

Sub sheetnamefromlist()
    Dim ws As Worksheet, wsNew As Worksheet
    Dim lRow As Long, i As Long
    Dim NewSheetName As String
    
    '~~> Set this to the relevant worksheet
    '~~> which has the range
    Set ws = ThisWorkbook.Sheets("LocalList")
    
    With ws
        '~~> Find last row
        lRow = .Range("B" & .Rows.Count).End(xlUp).Row
        
        '~~> Loop through the range
        For i = 4 To lRow
            NewSheetName = .Cells(i, 2).Value2
            
            '~~> Check if there is already a worksheet with that name
            If Not SheetExists(NewSheetName) Then
                '~~> Create the worksheet and name it
                With ThisWorkbook
                    .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = NewSheetName
                End With
            End If
        Next i
    End With
End Sub

'~~> Function to check if the worksheet exists
Private Function SheetExists(shName As String) As Boolean
    Dim shNew As Worksheet
    
    On Error Resume Next
    Set shNew = ThisWorkbook.Sheets(shName)
    On Error GoTo 0
    
    If Not shNew Is Nothing Then SheetExists = True
End Function

我的假设

  1. 所有单元格都有有效值,即可用于工作表名称。如果没有,那么您也必须处理该错误。
  2. 工作簿(不是工作表)不受保护

推荐阅读