gpt4 book ai didi

excel - 删除所有工作表中除指定列外的所有列

转载 作者:行者123 更新时间:2023-12-02 17:32:01 25 4
gpt4 key购买 nike

我想删除 Excel 工作簿的所有工作表中的所有列,除了以下名称的列:

Date
Name
Amount Owing
Balance

以下代码在事件工作表中运行:

Sub DeleteSelectedColumns()
Dim currentColumn As Integer
Dim columnHeading As String

For currentColumn = ActiveSheet.UsedRange.Columns.Count To 1 Step -1
columnHeading = ActiveSheet.UsedRange.Cells(1, currentColumn).Value

'Check whether to preserve the column
Select Case columnHeading
'Insert name of columns to preserve
Case "Date", "Name", "Amount Owing", "Balance"
'Do nothing
Case Else
'Delete the column
ActiveSheet.Columns(currentColumn).Delete
End Select
Next
End Sub

如何修改此代码以应用于所有工作表?

最佳答案

您正在寻找这样的东西:

Sub DeleteSelectedColumns()

Dim ws As Worksheet
Dim rDel As Range
Dim HeaderCell As Range
Dim sKeepHeaders As String
Dim sDelimiter as String

sDelmiter = ":"
sKeepHeaders = Join(Array("Date", "Name", "Amount Owing", "Balance"), sDelimiter)

For Each ws In ActiveWorkbook.Sheets
Set rDel = Nothing
For Each HeaderCell In ws.Range("A1", ws.Cells(1, ws.Columns.Count).End(xlToLeft)).Cells
If InStr(1, sDelimiter & sKeepHeaders & sDelimiter, sDelimiter & HeaderCell.Value & sDelimiter, vbTextCompare) = 0 Then
If Not rDel Is Nothing Then Set rDel = Union(rDel, HeaderCell) Else Set rDel = HeaderCell
End If
Next HeaderCell
If Not rDel Is Nothing Then rDel.EntireColumn.Delete
Next ws

End Sub

关于excel - 删除所有工作表中除指定列外的所有列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50515150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com