excel - 使用列表中的名称创建新工作表
问题描述
我对 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
解决方案
这是我快速写的东西
一些事情
- 不要像那样找到最后一行。你可能想看这个
- 不要
.Text
用来读取单元格的值。您可能想了解.text、.value 和 .value2 之间的区别是什么? - 在尝试创建其他工作表之前检查工作表是否存在,您将收到错误消息。
这是你正在尝试的吗?
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
我的假设
- 所有单元格都有有效值,即可用于工作表名称。如果没有,那么您也必须处理该错误。
- 工作簿(不是工作表)不受保护
推荐阅读
- python - 格式化一个没有尾随零的浮点数
- flutter - Flutter sharedpreferences 在应用重启后获取数据
- angular - 如何修复Angular Http Post Request发送多次?
- android - Android 资源链接失败,错误:未找到属性 defaultNavHost (aka ...),未找到 ttribute navGraph (aka...)
- google-people-api - 向 Google People API 请求时出现 429 错误
- django - 尽管设置,表单不需要 Django 小部件
- visual-studio - 为 VS2017 安装 GitHub 扩展“此扩展不可安装在任何当前安装的产品上”
- sql - pg_shadow 表在哪里?
- excel - 在范围内的值上构建组合框列表跳过空单元格
- ios - 是否可以使用 xcodebuild 而完全不使用 Xcode 来开发 iOS 应用程序?