excel - 使用 VBA 过滤和移动数据
问题描述
我正在尝试找到一种方法来快速过滤并将单元格范围切割到另一张纸上
准确地说:
Private Sub CommandButton1_Click()
Dim rng As Range, cell As Range
Set rng = Range("a2:a100")
For Each cell In rng
If Sheet1.Range("a2").Offset(1) = "DE" Then
Sheet1.Range("b2:f2").Cut Sheet2.Range("b2:f2")
End If
Next cell
End Sub
我知道此代码仅限于 Cell(A2)。
我需要我的代码通过 Range ("a2:a100") 以及它是否包含值 Exp。“DE”将范围(b2:f2)剪切到下一张纸
经验。
如果单元格a2包含“DE”,则需要剪切范围(“b2:f2”)如果单元格a5包含“DE”,则需要剪切范围(“b5:f5”)exc ...
解决方案
切割标准行 ( For Each...Next
)
- 使用数组或使用
AutoFilter
肯定会更有效。
Option Explicit
Sub CutCriteriaRows()
Const sCol As String = "A"
Const sdCols As String = "B:F"
Const sfRow As Long = 2
Const sCriteria As String = "DE"
Const dCol As String = "B"
Dim sws As Worksheet: Set sws = Sheet1
Dim dws As Worksheet: Set dws = Sheet2
Dim slRow As Long: slRow = sws.Cells(sws.Rows.Count, sCol).End(xlUp).Row
Dim srCount As Long: srCount = slRow - sfRow + 1
Dim srg As Range: Set srg = sws.Cells(sfRow, sCol).Resize(srCount)
Dim scrg As Range
Dim sCell As Range
For Each sCell In srg.Cells
If CStr(sCell) = sCriteria Then
Set scrg = RefCombinedRange(scrg, sCell)
End If
Next sCell
If scrg Is Nothing Then Exit Sub
Dim dlRow As Long: dlRow = dws.Cells(dws.Rows.Count, dCol).End(xlUp).Row
Dim dfCell As Range: Set dfCell = dws.Cells(dlRow + 1, dCol)
With Intersect(scrg.EntireRow, sws.Columns(sdCols))
.Copy dfCell
.EntireRow.Delete
End With
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a reference to a range combined from two ranges.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefCombinedRange( _
ByVal CombinedRange As Range, _
ByVal AddRange As Range) _
As Range
If CombinedRange Is Nothing Then
Set RefCombinedRange = AddRange
Else
Set RefCombinedRange = Union(CombinedRange, AddRange)
End If
End Function
推荐阅读
- java - 不抛出主要的次要不受支持的异常
- typo3 - 错字3 setEnableFieldsToBeIgnored 不起作用
- c# - 对角射击子弹
- javascript - 使用事件修改 javascript 文件
- log4net - 如何使用 Log4net 在代码中禁用特定方法调用的日志记录
- python - 括号、引号等的 Ipython shell 自动补全
- php - 如何在 Firefox 移动端而不是原生应用上打开 Google Play 商店
- java - 如何从 Java 中的 Stream 中创建 2D(二维)数组?
- django - django擦除模型的重复值
- r - 从文本/句子中提取搭配