【问题标题】:How to incorporate a with statement with an if statement?如何将 with 语句与 if 语句合并?
【发布时间】:2019-11-14 01:15:45
【问题描述】:

我一直在编写代码以弹出一个消息框,您可以在其中键入工作表的名称,然后它将在所有其他具有该名称的工作表的末尾创建一个新工作表。

在谷歌搜索的帮助下,我制作了一个弹出 inputbox 的代码,我在其中为新工作表写了一个我想要的名称,并使用 with 语句,它在所有结束时创建它我的其他床单。

我遇到的问题是 if 语句,它应该说如果此名称不存在,则继续运行代码,如果名称确实存在,则退出子(不要继续处理下面的代码)。我将If Not xSht Is Nothing Then 写成If xSht Is Nothing Then 来工作,但这会创建两个if 语句,所以第一部分完全无效。我也尝试将其编写为 else 语句,但随后它跳过了 msgbox 并且由于下面的 with 语句仍然创建了一个新工作表。

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>

【问题讨论】:

    标签: excel vba if-statement with-statement


    【解决方案1】:

    试试这个。您可以在检查工作表是否存在时关闭错误。在输入名称后定义变量,否则会出现另一个错误。

    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
    

    【讨论】:

    • 非常感谢!!我一直在努力解决这个问题,现在终于成功了!
    【解决方案2】:

    颠倒顺序:

    Set xSht = Sheets(xName)
    

    和:

    xName = InputBox("Enter Sheet Name")
    

    (可能还有其他问题)

    【讨论】:

    • 感谢您的帮助。它对第一部分有所帮助。
    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2020-02-29
    相关资源
    最近更新 更多