一次select所有单元格超出限制值

我可以只select区域中包含数字的单元格: Region.SpecialCells(xlCellTypeConstants , xlNumbers)

但我不知道如何只select数字上方的单元格。 例如1.0以上的那些

我有一个大号的数字表,我想要将所有数字都设置为1以上,并将它们设置为1.我喜欢这样做,而不必在每个单元格上循环。

谢谢!

我说,忘了SpecialCells 。 只需将所有需要testing的单元格加载到Variant数组中。 然后在这个数组上循环,并做你的封顶。 这是非常有效的,这与在表单中循环单元格相反。 最后,把它写回工作表。

使用包含0到2之间的随机值的50,000个单元格,此代码在我的古董笔记本电脑上运行0.2秒。

额外的好处是这是相当清晰和可读的代码,并且您可以完全控制将要操作的范围。

 Dim r As Range Dim v As Variant Set r = Sheet1.UsedRange ' Or customise it: 'Set r = Sheet1.Range("A1:HZ234") ' or whatever. v = r ' Load cells to a Variant array Dim i As Long, j As Long For i = LBound(v, 1) To UBound(v, 1) For j = LBound(v, 2) To UBound(v, 2) If IsNumeric(v(i, j)) And v(i, j) > 1 Then v(i, j) = 1 ' Cap value to 1. End If Next j Next i r = v ' Write Variant array back to sheet. 

下面的这个方法避免了逐个单元循环 – 虽然它比你的范围循环代码长得多,但是我希望避免逐个单元格范围循环

我已经从一个快速的方法更新我的代码来确定解锁的单元格范围,以提供一个非单元格循环方法

  1. 代码将检查SpecialCells(xlCellTypeConstants , xlNumbers)SpecialCells(xlCellTypeConstants , xlNumbers)存在SpecialCells(xlCellTypeConstants , xlNumbers)以进行更新(error handling应始终与SpecialCells一起使用
  2. 如果这些单元格存在,则创build一个工作表 ,如果主表单上的值大于1,则将公式插入步骤1的范围内以创build故意错误(1/0)
  3. SpecialCells(xlCellTypeFormulas, xlErrors)返回值大于1的工作表中的单元格范围(到rng3
  4. rng3中的所有区域都设置为1, rng3.Value2=1

     Sub QuickUpdate() Dim ws1 As Worksheet Dim ws2 As Worksheet Dim rng1 As Range Dim rng2 As Range Dim rng3 As Range Dim lCalc As Long Set ws1 = ActiveSheet On Error Resume Next Set rng1 = ws1.Cells.SpecialCells(xlConstants, xlNumbers) On Error GoTo 0 'exit if there are no contants with numbers If rng1 Is Nothing Then Exit Sub 'disable screenupdating, event code and warning messages. 'set calculation to manual With Application .ScreenUpdating = False .EnableEvents = False .DisplayAlerts = False lCalc = .Calculation .Calculation = xlCalculationManual End With ws1.Copy After:=Sheets(Sheets.Count) Set ws2 = ActiveSheet 'test for cells constants > 1 ws2.Cells.SpecialCells(xlConstants, xlNumbers).FormulaR1C1 = "=IF('" & ws1.Name & "'!RC>1,1/0,'" & ws1.Name & "'!RC)" On Error Resume Next Set rng2 = ws2.Cells.SpecialCells(xlCellTypeFormulas, xlErrors) On Error GoTo 0 If Not rng2 Is Nothing Then Set rng3 = ws1.Range(rng2.Address) rng3.Value2 = 1 Else MsgBox "No constants < 1" End If ws2.Delete 'cleanup user interface and settings With Application .ScreenUpdating = True .EnableEvents = True .DisplayAlerts = True lCalc = .Calculation End With 'inform the user of the unlocked cell range If Not rng3 Is Nothing Then MsgBox "Cells updated in Sheet " & vbNewLine & ws1.Name & vbNewLine & " are " & vbNewLine & rng3.Address(0, 0) Else MsgBox "No cells updated in " & ws1.Name End If End Sub 

循环有什么危害? 我刚刚在39900个单元格上testing了这个代码,并以2秒的速度运行。

 Sub Sample() Dim Rng As Range, aCell As Range Set Rng = Cells.SpecialCells(xlCellTypeConstants, xlNumbers) For Each aCell In Rng If aCell.Value > 1 Then aCell.Value = 1 Next aCell End Sub 

我唯一担心的是使用SpecialCells,因为它们是不可预测的,因此我很less使用它们。

也看看这个知识库文章: http : //support.microsoft.com/?kbid=832293