excel - VBA不重命名新工作表
问题描述
下面的代码应该添加一个新工作表,然后从输入框中为其命名。我已经经历了几次迭代,但无法让它发挥作用。
Option Explicit
Dim oWS as Worksheet, sName as String
Again:
sName = Inputbox ("Enter Sheet Name")
If sName = vbNull Then Exit Sub
For Each oWs in Worksheets
If LCase (sName) = LCase (oWS.Name) Then GoTo Again
Next oWS
Set oWS = Worksheets.Add(,ActiveSheet)
End Sub
解决方案
我会使用,Application.InputBox
因为如果为空,它会返回 false。在Goto
你的代码中包含语句有点像在你的房子脏的时候邀请人们过来。最后,添加了一些代码来处理无效的工作表名称。
Sub AddWorksheet()
Dim result As Variant
Dim ws As Worksheet
Do
result = Application.InputBox(Prompt:="Enter Sheet Name", Title:=IIf(Len(result) = 0, "Create Worksheet", result & " - Exists"), Type:=2)
If result = False Then Exit Sub
Loop Until Not WorksheetExists(result)
Set ws = ThisWorkbook.Worksheets.Add
On Error Resume Next
ws.Name = result
If Err.Number <> 0 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
If MsgBox("Try Again?", vbYesNo, "Invalid Name") = vbYes Then AddWorksheet
Exit Sub
End If
On Error GoTo 0
End Sub
Function WorksheetExists(result As Variant) As Boolean
Dim ws As Worksheet
For Each ws In Worksheets
If LCase(result) = LCase(ws.Name) Then
WorksheetExists = True
Exit Function
End If
Next
End Function
推荐阅读
- ruby-on-rails - 从 rails-assets.org 采购宝石有什么作用?
- pdf-conversion - 文本对齐:在生成的 evoPDF 上对齐
- sas - SAS Proc GLM 预测输出
- java - 更新到实现 'com.google.android.gms:play-services-ads:15.0.2' 和类路径 'com.google.gms:google-services:3.3.0' 后出现 Gradle 错误
- powershell - 将 SSL 自动化任务添加到管道
- javascript - 如何在 React Admin 包中显示来自服务器端验证的自定义错误消息?
- postgresql - PostgreSQL/JPA - 在 import.sql 文件中导入函数?
- jasper-reports - 将字符串参数传递给子报表数据集
- java - 单击包含 observableArray 的 tableView 内部的 ImageView 后执行事件
- c++ - 为什么在 boost 图形库的访问者中使用 CRTP 模式?