我正在尝试自动过滤SHEET 2中的活动单元格(在SHEET 1的A列中)。然后我有一个IF语句,它计算可见行的数量,如果它大于1(排除标题),那么我想在SHEET 3中插入新行并剪切并粘贴将SHEET 1中的自动过滤的行添加到SHEET 3中的新行。
然后清除SHEET 1中的自动过滤器,然后在SHEET 1中插入新行,然后将SHEET 2中活动单元格行的值剪切并粘贴到新行中在SHEET 1中。如果SHEET 1中的自动过滤器没有结果,则ELSE STATEMENT清除SHEET 1中的自动过滤器,在SHEET 1中插入新行,然后从剪切并粘贴活动单元的行的值SHEET 2放入SHEET 1中的新行。
当前,如果SHEET 2中的自动过滤器结果出现在任何行中>第2行,我似乎都无法使我的代码正常工作。这是我当前的代码,我已评论过以帮助导航:] >
Sub Autofilter_Macro()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet
Set sh1 = Sheet1
Set sh2 = Sheet2
Set sh3 = Sheet3
Dim rng As Range
Dim AC As Integer
AC = ActiveCell.Row
sh1.AutoFilterMode = False 'Clears any AutoFilters from Sheet1
sh1.Range("A:A").AutoFilter Field:=1, Criteria1:=ActiveCell.Value 'AutoFilters SHEET 1 column "A" based off the ActiveCell Row in SHEET 2
Set rng = sh1.UsedRange.SpecialCells(xlCellTypeVisible) 'Sets rng to visible cells
If (rng.Rows.Count > 1) Then 'Counts the # of visible rows
sh3.Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow 'Inserts an empty row (with the same format as the one below it) into row 2 of SHEET 3
sh3.Range("A2:CK2").Value = rng.Offset(rowOffSet:=1).Value 'Sets the new empty row's values in SHEET 3 = the values of the Autofiltered row in SHEET 1
sh1.ShowallData 'Clears any Autofilters from SHEET 1
sh1.Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow 'Inserts an empty row (with the same format as the one below it) into row 2 of SHEET 1
sh1.Range("A2:CK2").Value = sh2.Range(Cells(AC, 1), Cells(AC, 89)).Value 'Sets the new empty row's values in SHEET 1 = the values of the ActiveCell row in SHEET 2
MsgBox "Replaced Main Database" 'MsgBox indicating what has executed
Else
sh1.Rows("2:2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrBelow 'Inserts an empty row (with the same format as the one below it) into row 2 of SHEET 1
sh1.Range("A2:CK2").Value = sh2.Range(Cells(AC, 1), Cells(AC, 89)).Value 'Sets the new empty row's values in SHEET 1 = the values of the ActiveCell row in SHEET 2
MsgBox "New Entry into Main Database"
End If
sh1.ShowallData 'Clears any Auotfilters from SHEET 1
End Sub
我正在尝试自动过滤SHEET 2中的活动单元格(在SHEET 1的A列中。然后,我有一个IF语句,该语句对可见行的数量进行计数,如果它大于1(排除标题),则...
问题是可见范围是不连续的,例如“ $ A $ 1:$ D $ 1,$ A $ 6:$ D $ 6”,因此rng.Offset(rowOffSet:= 1)将始终给出$ A $ 2:$ D $ 2。范围有一个areas property。使用rng.areas.count您可以执行类似的操作