首页 > 解决方案 > 删除excel vba中工作表的嵌套If循环不执行其分配的功能

问题描述

我的代码有问题,我似乎无法修复。基本上我想做的是有 2 个嵌套的 if 条件。其中一个检查工作表的名称是否以“properties_auto”开头,以避免删除与它们无关的工作表。第二个检查名称是否包含我正在使用的两个“存款”之一。如果满足第一个条件但不满足第二个条件,则删除工作表,以避免出现无用的工作表。这里的问题是代码似乎删除了所有在其代码中包含 properties_auto 的工作表。

这是代码:

Dim oSheet As Excel.Worksheet
Dim count_heat As Integer
count_heat = 0

For Each oSheet In ActiveWorkbook.Sheets
    count_heat = 0
    For i = 1 To deposits.count
        If InStr(UCase(oSheet.Name),UCase("Properties_auto")) Then
            If InStr(UCase(oSheet.Name),UCase(deposits(i))) Then
            Else
                count_heat = count_heat + 1
            End If
        Else
        End If
    Next i
    If count_heat > 0 Then
        oSheet.Delete
    Else
    End If
Next

标签: excelvba

解决方案


您将存款数组中的每个元素与工作表名称进行比较。即使一两个匹配,也必须有其他不匹配并且将 count_heat 增加到零以上。

更改 count_heat 值的条件。

If count_heat = deposits.count Then 'there were no matches at all
    oSheet.Delete
End If

一旦找到与其中一个存款的匹配项,您还可以通过退出 For ... Next 循环来保存一些循环。请注意,这仍然必须与上面的 If 语句调整一起使用。

If InStr(UCase(oSheet.Name),UCase(deposits(i))) Then
    exit for
Else
    count_heat = count_heat + 1
End If

推荐阅读