我有经常从源工作簿导出的数据(格式是一致的,即所有列名都位于第1行)。我只需要在整个工作表中偶尔间隔大约8个左右列的数据(" Sheet1")。下面是我到目前为止所做的代码。
我有两个问题,
宏正在删除我的所有数据,
我的If语句非常低效。我想创建一个变量,其中包含所有包含我不想删除的列名的字符串。我正在考虑创建一个数组,但我不确定我的循环是否会正常运行
i.e., colNames = array("Col 1 that I want to keep", "Col 2", etc)
守则:
Sub test2()
Dim currentSht As Worksheet
Dim i As Integer
Dim lastRow As Long, lastCol As Long
Dim startCell As Range
Set currentSht = ActiveWorkbook.Sheets("Sheet1")
Set startCell = currentSht.Range("A1")
lastRow = startCell.SpecialCells(xlCellTypeLastCell).Row
lastCol = startCell.SpecialCells(xlCellTypeLastCell).Column
With currentSht
For i = lastCol To 1 Step -1
If .Cells(1, i).Text <> "First Name" Or .Cells(1, i).Text <> "Last Name" Or .Cells(1, i).Text <> "OB Hours(hr)" Or .Cells(1, i).Text <> "OB Talk Time (TT)" Or .Cells(1, i).Text <> "OB ACW Time" Or .Cells(1, i).Text <> "Handled-OB" Or .Cells(1, i).Text <> "Handled-OB/hr" Or .Cells(1, i).Text <> "TT Avg" Or .Cells(1, i).Text <> "Max Talk Time" Then
Columns(i).EntireColumn.Delete
End If
Next i
End With
End Sub
再次感谢大家。
答案 0 :(得分:0)
关于你的第一个问题:
将if语句中的Or
更改为And
到你的第二个:
Sub test2()
Dim currentSht As Worksheet
Dim i As Long, j As Long
Dim lastRow As Long, lastCol As Long
Dim startCell As Range
Dim colnames
Dim here As Boolean
colnames = Array("First Name", "Last Name", "OB Hours(hr)", "OB Talk Time (TT)", "OB ACW Time", "Handled-OB", "Handled-OB/hr", "TT Avg", "Max Talk Time")
Set currentSht = ActiveWorkbook.Sheets("Sheet1")
Set startCell = currentSht.Range("A1")
lastRow = startCell.SpecialCells(xlCellTypeLastCell).Row
lastCol = startCell.SpecialCells(xlCellTypeLastCell).Column
With currentSht
For i = lastCol To 1 Step -1
here = False
For j = LBound(colnames) To UBound(colnames)
If .Cells(1, i).Value = colnames(j) Then
here = True
Exit For
End If
Next j
If Not here Then
Columns(i).EntireColumn.Delete
End If
Next i
End With
End Sub