简体   繁体   English

如何将with语句与if语句合并?

[英]How to incorporate a with statement with an if statement?

I've been working on a code to have a message box pop up that you can type in the name of a sheet and then it will create a new sheet at the end of all the other ones with that name. 我一直在编写一个代码,弹出一个消息框,您可以键入工作表的名称,然后它将在所有其他具有该名称的工作表的末尾创建一个新工作表。

With the help of googling, I was able to make a code that pops up an inputbox where I write a name that I want for the new sheet and with a with-statement, it creates it at the end of all my other sheets. 在谷歌搜索的帮助下,我能够编写一个代码,弹出一个输入inputbox ,在其中输入我想要为新工作表命名的名称,并带有with语句,它将在所有其他工作表的末尾创建该代码。

What I am having problems with is the if-statement, which should say that if this name does not exist continue running the code and if the name does exist exit sub (don't continue processing the codes beneath). 我遇到的问题是if语句,它应该说,如果该名称不存在,请继续运行代码,如果该名称确实存在,请退出sub(不要继续处理下面的代码)。 I got the If Not xSht Is Nothing Then to work by writing it as If xSht Is Nothing Then , but that creates two if statements, so the first part gets completely nullified. 我得到If Not xSht Is Nothing Then的工作方式,就是将它编写为If xSht Is Nothing Then ,但这会创建两个if语句,因此第一部分将完全无效。 I also tried writing it as an else statement, but then it jumps over the msgbox and still creates a new sheet because of the with statement below. 我也尝试将其编写为else语句,但是由于下面的with语句,它跳过了msgbox并仍然创建了一个新表。

Dim ws As Worksheet
Dim xName As String
Dim xSht As Object

Set xSht = Sheets(xName)
xName = InputBox("Enter Sheet Name")

If xName = "" Then Exit Sub

If Not xSht Is Nothing Then
    MsgBox ("Name already exists")
    Exit Sub
End If

With ThisWorkbook   'Adds new sheet with the name it has been given
    Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
    ws.Name = xName
End With

<More code>

Reverse the order of: 颠倒顺序:

Set xSht = Sheets(xName)

and: 和:

xName = InputBox("Enter Sheet Name")

(there may be other problems) (可能还有其他问题)

Try this. 尝试这个。 You can turn off errors while you check if the sheet exists. 您可以在检查工作表是否存在时关闭错误。 Define the variable after the name has been entered otherwise you will get another error. 输入名称后定义变量,否则将出现另一个错误。

Sub x()

Dim ws As Worksheet
Dim xName As String
Dim xSht As worksheet

xName = InputBox("Enter Sheet Name")
If xName = "" Then Exit Sub

On Error Resume Next 'avoids error if sheet doesn't exist
Set xSht = Sheets(xName)
On Error GoTo 0      'turn off error avoidance

If Not xSht Is Nothing Then
    MsgBox "Name already exists"
    Exit Sub
End If

With ThisWorkbook
    Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
    ws.Name = xName
End With

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM