excel - 自动过滤、复制和插入。即使代码运行没有错误,也不会插入数据
问题描述
下面的代码“完美”运行。我可以看到数据被过滤了,我可以看到选择了正确的范围。而且我假设该范围内的数据被复制。
但是,当尝试插入复制的数据时,什么也没有出现。我可以看到应该复制的范围内有数据。
奇怪的是,我知道它在某个时候有效,但突然间就没有了。
Const sFILE_PATH As String = "C:\Downloads\"
Const sEXTENSION As String = ".xlsm"
Dim lastrow As Long
Dim lastrow_Offset As Long
Dim wbk As Workbook
Dim sFileName As String
sFileName = "2018"
Set wbk = Workbooks(sFileName & sEXTENSION)
lastrow_Offset = ThisWorkbook.Sheets("Test").Cells(Rows.Count, "h").End(xlUp).Row
lastrow = wbk.Sheets("Acc").Cells(Rows.Count, "C").End(xlUp).Row
Application.ScreenUpdating = False
With wbk.Sheets("Acc")
.AutoFilterMode = False
.Range("A4:AL" & lastrow).AutoFilter Field:=37, Criteria1:="=NC", Operator:=xlFilterValues
.Range("A4:AL" & lastrow).AutoFilter Field:=38, Criteria1:="=New", Operator:=xlFilterValues
Debug.Print Range("C5:C" & lastrow).SpecialCells(xlCellTypeVisible).Address
.Range("C5:C" & lastrow).SpecialCells(xlCellTypeVisible).Copy
.AutoFilterMode = False
End With
ThisWorkbook.Sheets("Test").Range("H26").Offset((lastrow_Offset + 1) - 26, 0).Insert
Application.ScreenUpdating = True
解决方案
You don't paste your data. The Insert
-command simply creates a new (empty) line, that's all.
Change your code to
With wbk.Sheets(1)
.AutoFilterMode = False
.Range("A4:AL" & lastrow).AutoFilter Field:=37, Criteria1:="=NC", Operator:=xlFilterValues
.Range("A4:AL" & lastrow).AutoFilter Field:=38, Criteria1:="=New", Operator:=xlFilterValues
lastrow_Offset = ThisWorkbook.Sheets("Test").Cells(Rows.Count, "H").End(xlUp).row
Dim destCell As Range
Set destCell = ThisWorkbook.Sheets("Test").Range("H26").Offset((lastrow_Offset + 1) - 26, 0)
.Range("C1:C" & lastrow).SpecialCells(xlCellTypeVisible).Copy destCell
.AutoFilterMode = False
End With
Update: as Siddharth Rout pointed out, I was wrong, the Insert
pastes data. However, it seems that this is not working if a non-contiguous range was selected for copy - as it is the most cases for filtered data.
In that case, either provide the destination-parameter already when copying the data (as I do in my code above) or use the PasteSpecial
-method of the destination range. I prefer to use the first method as it doesn't keep the data in the paste-buffer, but that's a minor thing.
推荐阅读
- excel - 将单元格的文本自动复制到整个 excel 文档的下 4 行中
- python - Python3 Websocket回调无法分配类成员函数
- c# - 如何在.net核心中将多个文件夹用于app.UseStaticFiles?
- java - 如何使用 Apache Beam 从 RabbitMQ 读取数据
- java - Java泛型类作为参数
- scala - scala字符串尾递归与模式匹配
- python-3.x - 如何或是否有必要在 python 中的类中定义属性类型
- java - RegEx 用于匹配变量和逗号之间的空格
- angular - 无法清除Angular 7中相同组件导航上的复选框
- ibm-cloud - 在 IBM Cloud 中使用 LogDNA