热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ExcelVBA基于多个表上的多个标题删除列-ExcelVBAtoRemoveColumnsBasedonMultipleHeadersonMultipleSheets

Wouldthebelowcodebeabletobemodifiedto1loopthroughallsheetsinaworkbookand2remove

Would the below code be able to be modified to 1 loop through all sheets in a workbook and 2 remove multiple columns based on their headers?

下面的代码是否能够修改为1循环遍历工作簿中的所有工作表,2根据其标题删除多个列?

example: "status","Status Name","Status Processes" etc.)? And then cycle through all sheets in the wkbk to do the same checks?

例如:“状态”,“状态名称”,“状态进程”等)?然后循环遍历wkbk中的所有工作表进行相同的检查?

Sub remove_columns()
    For i = ActiveSheet.Columns.Count To 1 Step -1
        If InStr(1, Cells(1, i), "Status") Then Columns(i).EntireColumn.Delete
    Next i
End Sub

3 个解决方案

#1


3  

dim a as long, w as long, vDELCOLs as variant, vCOLNDX as variant
vdelcols = array("status","Status Name","Status Processes")
with thisworkbook
    for w=1 to .worksheets.count
        with worksheets(w)
            for a=lbound(vdelcols) to ubound(vdelcols)
                vcolndx=application.match(vdelcols(a), .rows(1), 0)
                if not iserror(vcolndx) then
                    .columns(vcolndx).entirecolumn.delete
                end if
            next a
        end with
    next w
end with

You obviously have less columns to delete than columns that exist. Look for matches to the columns to delete rather than comparing every column to the delete list.

显然,要删除的列比存在的列少。查找要删除的列的匹配项,而不是将每列与删除列表进行比较。

This looks (case-insensitive) for the column names in row 1.

这看起来(不区分大小写)第1行中的列名称。

#2


2  

I'd go like follows

我会像以下一样

Sub Main()
    Dim sh As Worksheet
    Dim i as Long

    For Each sh In ThisWorkbook.Sheets
        With sh.UsedRange
            For i = .columns.Count To 1 Step -1
                If InStr(1, LCase(.columns(i).cells(1)), "status") Then .columns(i).EntireColumn.Delete
            Next
        End With
    Next
End Sub

#3


1  

You need to properly reference the sheet, easy using With and you can use LCase() to avoid case sensitivity :

您需要正确引用工作表,轻松使用With,您可以使用LCase()来避免区分大小写:

Sub remove_columns()
    Dim wS As WorkSheet
    For Each wS in ThisWorkbook.Worksheets
        With wS
            For i = .Columns.Count To 1 Step -1
                If InStr(1, LCase(.Cells(1, i)), LCase("Status")) Then _
                    .Columns(i).EntireColumn.Delete
            Next i
        End With 'wS
    Next wS
End Sub

推荐阅读
author-avatar
sisihg_676
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有