excel - 一次选择高于限制值的所有单元格

标签 excel vba

我只能选择区域中包含数字的单元格: Region.SpecialCells(xlCellTypeConstants , xlNumbers)

但我不知道如何仅选择数字上方的单元格。例如1.0以上的

我有一张包含数字的大工作表,我想将所有数字设置为 1 以上,并将它们设置为 1。我很乐意这样做,而不必在每个单元格上循环。

谢谢!

最佳答案

下面的这种方法避免了逐个单元格的循环 - 虽然它比您的范围循环代码长得多,但我同意您的偏好,尽可能避免逐个单元格的范围循环

我已从 A fast method for determining the unlocked cell range 更新了我的代码提供非逐个单元循环方法

  1. 代码检查SpecialCells(xlCellTypeConstants , xlNumbers) 存在于要更新的​​工作表上(错误处理应始终是 与 SpecialCells 一起使用
  2. 如果这些单元格存在,则会创建一个工作表,并将一个公式插入到步骤 1 的范围内,以在主工作表上的值不存在的情况下创建故意错误(1/0) >1
  3. SpecialCells(xlCellTypeFormulas, xlErrors) 返回工作表中值大于 1 的一系列单元格(放入 rng3)
  4. rng3 中的所有区域均通过 rng3.Value2=1 设置为 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
    

关于excel - 一次选择高于限制值的所有单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8827559/

相关文章:

excel - 如果连续值高于基线值,则更改图表标记颜色

vba - 对于 VBA 中的每个循环意外地跳过行

html - 使用 VBA 操作 IE 以登录和预订类(class)

带有宏的 VBA 复印表

excel - 尝试使用 pivot 和 ssis 导入 excel 文件

arrays - 将项目附加到excel vba中的数组时下标超出范围

excel - 如何使用Excel正确读取带有点分隔符的小数?

vba - 使用 VBA 下载网页的 HTML 内容是否会引发 Google Analytics 事件?

vba - 将pdf放在新创建的同名文件夹中

mysql - 将所有数据从 MySQL 数据库导出到电子表格