我尝试使用应该
>=0.05
I2=B2-E2
; I3=B3-E3
等等这个宏是由 Jeeped 创建的:
Sub sort1()
Dim m As Variant
With ActiveSheet
'delete rows 1:6
.Range("1:6").EntireRow.Delete Shift:=xlUp
'new column header for column I
Range("I1") = "diff"
'sort A:I on column H (ascending)
With .Range("A:I")
.Sort Key1:=.Columns(8), Order1:=xlAscending, Header:=xlYes
End With
'find >=0.05
m = Application.Match(0.05, .Range("H:H"), 0)
If IsError(m) Then m = Application.Match(0.05, .Range("H:H"))
'delete rows (>=0.05):<bottom of worksheet>
.Range(.Cells(m, "A"), .Cells(.rows.Count, "A")).EntireRow.Delete Shift:=xlUp
'new formula for column I data range
.Range("I2:I" & m - 1).FormulaR1C1 = "=RC[-7]-RC[-4]"
'calculate (actually unnecessary, putting in new formulas forces true calculation)
.Calculate
'sort A:I on column I (ascending)
With .Range("A:I")
.Sort Key1:=.Columns(9), Order1:=xlAscending, Header:=xlYes
End With
End With
End Sub
它以前工作过,但现在它停在字符串上.Range(.Cells(m, "A"), .Cells(.rows.Count, "A")).EntireRow.Delete Shift:=xlUp
它说Run-time error '13': Type mismatch
请帮忙!
最佳答案
在不知道该子正在处理的数据的情况下,很难猜出为什么会出现该错误。但是,我敢打赌 Application.Match
函数在 H
列中找不到任何值小于或等于 0.05
, 所以 m = #N/A
你不能通过#N/A
到.Cells()
属性(property)。
如果是这种情况(您可以在出现错误后检查它是否在立即窗口中),尝试删除行并仅在 MATCH
时进行排序那是成功的:
Sub sort1()
'begin your code here
'find >=0.05
m = Application.Match(0.05, .Range("H:H"), 0)
If IsError(m) Then m = Application.Match(0.05, .Range("H:H"))
If Not IsError(m) Then
'delete rows (>=0.05):<bottom of worksheet>
.Range(.Cells(m, "A"), .Cells(.rows.Count, "A")).EntireRow.Delete Shift:=xlUp
'new formula for column I data range
.Range("I2:I" & m - 1).FormulaR1C1 = "=RC[-7]-RC[-4]"
'calculate (actually unnecessary, putting in new formulas forces true calculation)
.Calculate
End If
'sort A:I on column I (ascending)
With .Range("A:I")
.Sort Key1:=.Columns(9), Order1:=xlAscending, Header:=xlYes
End With
'Continue your code here
End Sub
附:您的代码目前并不完全按照您所说的那样做:您想删除所有大于或等于
0.05
的行,但如果您没有完全等于 0.05
的值,并具有如下值:(0, ..., 0.048, 0.049, 0.051, 0.052, ...)
在您的 H
列,然后这行代码:If IsError(m) Then m = Application.Match(0.05, .Range("H:H"))
将找到小于或等于 0.05
的最大值,即 0.049
在我们的假设数据中。然后这行代码:
.Range(.Cells(m, "A"), .Cells(.rows.Count, "A")).EntireRow.Delete Shift:=xlUp
将删除具有 0.049
值的行到最后(0.049
包括在内)。您的代码删除了比您想要的多一个值,但是由于您之前说过它可以按您的意愿工作,所以我没有更改它。
如果您想纠正这种行为,您需要在
m
中添加一个第二次使用MATCH
:If IsError(m) Then m = Application.Match(0.05, .Range("H:H")) + 1
关于excel - 排序和删除行。运行时错误 '13' : Type mismatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72743526/