VBA筛选和复制-较短的例程?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VBA筛选和复制-较短的例程?相关的知识,希望对你有一定的参考价值。

是否有可能创建例程来缩短我在下面编写的代码?目前,正在复制相同的过程,但要重复x次。

Sub FilterandTrans()
Dim LastRow As Long

With Worksheets("Sheet1")

.Range("N:N").Replace What:="inf", Replacement:="0", LookAt:=xlPart, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

LastRow = .Range("M" & .Rows.Count).End(xlUp).Row

.Range("$M:$M").AutoFilter
.Range("$M:$M").AutoFilter field:=1, Criteria1:="Alpha"
.Range("N2:N" & LastRow).SpecialCells(xlCellTypeVisible).Copy Destination:=ThisWorkbook.Sheets(2).Range("a2")

'shorten below?

.Range("$M:$M").AutoFilter
.Range("$M:$M").AutoFilter field:=1, Criteria1:="Beta"
.Range("N2:N" & LastRow).SpecialCells(xlCellTypeVisible).Copy Destination:=ThisWorkbook.Sheets(2).Range("b2")

.Range("$M:$M").AutoFilter
.Range("$M:$M").AutoFilter field:=1, Criteria1:="Delta"
.Range("N2:N" & LastRow).SpecialCells(xlCellTypeVisible).Copy Destination:=ThisWorkbook.Sheets(2).Range("c2")

.Range("$M:$M").AutoFilter
.Range("$M:$M").AutoFilter field:=1, Criteria1:="Gamma"
.Range("N2:N" & LastRow).SpecialCells(xlCellTypeVisible).Copy Destination:=ThisWorkbook.Sheets(2).Range("d2")

.Range("$M:$M").AutoFilter
.Range("$M:$M").AutoFilter field:=1, Criteria1:="Rho"
.Range("N2:N" & LastRow).SpecialCells(xlCellTypeVisible).Copy Destination:=ThisWorkbook.Sheets(2).Range("e2")

.AutoFilterMode = False


End With
End Sub
答案
Sub FilterandTrans() Dim LastRow As Long With Worksheets("Sheet1") .Range("N:N").Replace What:="inf", Replacement:="0", LookAt:=xlPart, _ SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False LastRow = .Range("M" & .Rows.Count).End(xlUp).Row Dim criteriadict As Object Dim key As Variant Set criteriadict = CreateObject("Scripting.Dictionary") 'Late bound Microsoft Scripting Runtime is the reference to early bind criteriadict.Add "Alpha", "a1" criteriadict.Add "Beta", "b1" criteriadict.Add "Delta", "c1" criteriadict.Add "Gamma", "d1" criteriadict.Add "Rho", "e1" For Each key In criteriadict .Range("$M:$M").AutoFilter .Range("$M:$M").AutoFilter field:=1, Criteria1:=key 'Alpha, Beta, ... .Range("N2:N" & LastRow).SpecialCells(xlCellTypeVisible).Copy Destination:=ThisWorkbook.Sheets(2).Range(criteriadict(key)) 'Range Value Next k .AutoFilterMode = False End With End Sub
另一答案
.Range("$M:$M").AutoFilter .Range("$M:$M").AutoFilter field:=1, Criteria1:=Array( _ "Alpha", "Beta", "Gamma", "Delta", "Rho"), Operator:=xlFilterValues .Range("N2:N" & LastRow).SpecialCells(xlCellTypeVisible).Copy Destination:=ThisWorkbook.Sheets(2).Range("a2")

以上是关于VBA筛选和复制-较短的例程?的主要内容,如果未能解决你的问题,请参考以下文章

我创建几个c文件,然后直接复制的例程C文件,编译错误Build target 'Target 1' compiling main.c... main

如何理解dspc6748的例程

递归列出文件的例程的奇怪错误

将例程的内容复制到内存中的另一个位置

使用hooku update在Drupal中更新和设置变量的例程

从.Net调用访问模块中的例程?