我正在研究sub()导入每月收到的.csv(这是我的第一个宏)。 该文件的结构非常简单:共有5列,行数可变。
在A列中有日期(dd / mm / yyyy),B代码,C名称,D和E统计信息(数字)。 在第一行中,我创建了一个带有标题的行。 这里的代码:
Sub ImportCSV()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;D:\File.csv", Destination:=Range("$A$1"))
Application.ScreenUpdating = False
.Name = "FileName"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileDecimalSeparator = "."
.TextFileThousandsSeparator = ","
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
Application.ScreenUpdating = True
End With
Range("A1").EntireRow.Insert
Cells(1, 1) = "DATE"
Cells(1, 2) = "CODE"
Cells(1, 3) = "NAME"
Cells(1, 4) = "STATS1"
Cells(1, 5) = "STATS2"
Rows("1:1").Select
Selection.Font.Bold = True
Selection.HorizontalAlignment = xlCenter
Columns("D").NumberFormat = "#,##0.00"
Columns("D").HorizontalAlignment = xlCenter
Columns("E").NumberFormat = "#,##0.00"
Columns("E").HorizontalAlignment = xlCenter
Range("A1:E1").Select
Selection.AutoFilter
Cells.Select
Cells.EntireColumn.AutoFit
Range("C2").Select
ActiveWindow.FreezePanes = True
End Sub
现在,我想用过滤器清洁这些纸:
希望一切都清楚...
答案 0 :(得分:1)
您可以在这里合作,并从中获得一些想法。我用一些示例数据做了一个例子。它有点广泛(阅读:它可以变得更紧凑),但我希望您能够理解这种情况。
样本数据:
示例代码:
Option Explicit
Sub Filtering()
Dim lr As Long
Dim rng As Range
With Sheet1 'Change according to your sheets CodeName
'Retrieve the last used row
lr = .Cells(.Rows.Count, 1).End(xlUp).Row
'Set your range object where you want to apply a filter
Set rng = .Range("A1:E" & lr)
With rng
'Apply first two filters in one go
.AutoFilter 3, Array("*X*", "*Y*"), xlFilterValues
'Test for visible rows and if so, delete them
If .SpecialCells(12).Count > 5 Then .Offset(1).Resize(lr - 1, 5).Rows.EntireRow.Delete
'Apply second filter
.AutoFilter 3, "<>*Z*", xlFilterValues
'Test for visible rows and if so, delete them
If .SpecialCells(12).Count > 5 Then .Offset(1).Resize(lr - 1, 5).Rows.EntireRow.Delete
'Remove filter
.AutoFilter
End With
End With
End Sub
结果: