我有一本工作簿,里面有很多张纸。我正在用数字进行网络爬虫,然后使每个工作表都以数字作为名称。如果已经将数字指定给工作表,我想显示一个错误。我还希望用户能够输入新的工作表名称,但是在执行此操作之前,程序会不断弹出自己的错误消息。
该数字在工作表的单元格D10中。
For Each Sheet In ThisWorkbook.Sheets
If Sheet.Name = Range("D10") Then
MsgBox ("ERROR: This Acct No has already been formulated")
NewName = InputBox("Please Rename:")
ActiveSheet.Name = NewName
ElseIf Sheet.Name <> Range("D10") Then
ActiveSheet.Name = Range("D10")
End If
Next Sheet
我希望弹出自己的消息,但Excel只会弹出自己的错误消息。
答案 0 :(得分:2)
尝试一下:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button class="talk">Talk</button>
<h3 class="content"></h3>
</body>
</html>
顺便说一句,我建议您避免使用ActiveSheet,而是将工作表分配给变量。
答案 1 :(得分:1)
Option Explicit
Sub TestMe()
Dim wks As Worksheet
Worksheets.Add After:=ActiveSheet
For Each wks In ThisWorkbook.Worksheets
With wks
If .Name = .Range("D10") Then
MsgBox ("ERROR: This Acct No has already been formulated")
.Name = InputBox("Please Rename:")
ElseIf .Name <> .Range("D10") Then
If Trim(.Range("D10")) = "" Then
.Range("D10") = Replace(Replace(Now, ":", "_"), "/", "_")
Application.Wait Now + #12:00:02 AM#
End If
.Name = .Range("D10").Value
End If
End With
Next wks
End Sub
根据How to avoid using Select in Excel VBA,这是一些方法,避免使用Activate
和Select
(具有讽刺意味的是,我离开了Worksheets.Add After:=ActiveSheet
)
.Range("D10") = Replace(Replace(Now, ":", "_"), "/", "_")
部分通过在下一行等待2秒-Application.Wait Now + #12:00:02 AM#
答案 2 :(得分:1)
创建一个返回布尔值的函数,而不是循环遍历每张工作表以检查重复项。如果工作表不存在,此函数将有一个错误;如果工作表存在,则此函数将没有任何错误。我们检查该错误,如果存在工作表,则返回True
,否则返回False
。
Option Explicit
Private Function SheetExists(wsName As String, Optional wb As Workbook = Nothing) As Boolean
Dim ws As Worksheet
On Error Resume Next
If wb Is Nothing Then
Set ws = Worksheets(wsName)
Else
Set ws = wb.Worksheets(wsName)
End If
SheetExists = (Err.Number = 0)
End Function
然后您的代码可以替换为以下代码,该代码将根据需要不断调用InputBox
多次,以防止用户输入另一个无效/重复的条目。为此,我合并了MsgBox
和InputBox
文本,当我们可以同时使用InputBox
通知 时,似乎没有必要向用户抛出两个提示。并要求新的输入。
Dim ws as Worksheet
Dim newName as String
Set ws = ActiveSheet ' would be better to avoid this, but OK.
newName = Range("D10").Value
While SheetExists(newName, ws.Parent)
newName = InputBox("ERROR: This Acct No has already been formulated!" & vbCrLf & vbCrLf & _
newName & " already exists! Enter new name:")
Wend
ws.Name = newName