简体   繁体   English

VBA:For...If...Delete 循环中的类型不匹配错误

[英]VBA: Type mismatch error in For...If...Delete loop

I'm creating a chart from VBA in Excel, which will be as its own sheet & not embedded in a sheet.我正在从 Excel 中的 VBA 创建一个图表,该图表将作为自己的工作表而不嵌入工作表中。 As such, at the beginning of the script, I want to check to see if the sheet name already exists & if so, deletes it.因此,在脚本的开头,我想检查工作表名称是否已经存在,如果存在,则将其删除。

My code below throws a Run-time error '13': Type mismatch error at the For statement, but I can't see any reason why.我下面的代码在 For 语句中引发Run-time error '13': Type mismatch错误,但我看不出任何原因。 Any ideas?有任何想法吗?

I'm using Excel in Office 365.我在 Office 365 中使用 Excel。

Sub CreateChart()
' Macro to create a chart based on a given cross section ID

Dim cht As Object
Dim xsID As Integer
Dim tabName As String
Dim ws As Worksheet

xsID = Worksheets("INPUT").Range("D6")

tabName = "XS_" & CStr(xsID)
Debug.Print tabName

For Each ws In ThisWorkbook.Sheets
    Debug.Print ws
    Application.DisplayAlerts = False
    If ws.Name = tabName Then
        ws.Delete
        Debug.Print "Sheet deleted."
    End If
    Application.DisplayAlerts = True
Next ws

If you're looking for a chart sheet, that's not a worksheet:如果您正在寻找图表,那不是工作表:

Dim myChart As Chart
For Each myChart In ThisWorkbook.Charts
    Debug.Print myChart.Name

    If myChart.Name = tabName Then
        myChart.Delete
    End If
Next

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

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