excel - 找到被占用的单元格

标签 excel vba office365

在 Win 10 中使用 Excel 365

我在定位/识别正在使用的工作表单元格时遇到了一个非常小的问题。例如,在单元格 A1 和单元格 H5 中有常量。单元格 B2 包含可溢出的动态数组常量:

={1,2,"",4,5,6;7,8,9,"",11,99;100,"",0,0,100,0}

enter image description here

因为这张表既有公式也有常量,我试了下我信得过的:

Sub LocateCellsWithStuffInThem()
    Dim rng As Range

    With ActiveSheet.Cells
        Set rng = Union(.SpecialCells(xlCellTypeFormulas), .SpecialCells(xlCellTypeConstants))
    End With
    MsgBox rng.Address(0, 0)
End Sub

这给出:

enter image description here

我希望看到 B2:G4,A2,H5

显然正在使用像 D2 这样的单元格。它是数组常量的一部分,即使 SpecialCells 不认为它填充了公式或常量并且长度为零!

如何将代码写入容易定位的已占用单元格?我是否必须遍历 UsedRange 中的所有单元格?

最佳答案

您可以循环公式单元格并添加溢出区域(如果有):

Sub LocateCellsWithStuffInThem()
    Dim rng As Range
    Dim rng2 As Range
    With ActiveSheet.Cells
        Set rng = .SpecialCells(xlCellTypeConstants)
        For Each rng2 In .SpecialCells(xlCellTypeFormulas).Cells
            If rng2.HasSpill Then
                Set rng = Union(rng2.SpillingToRange, rng)
            Else
                Set rng = Union(rng2, rng)
            End If
        Next rng2
    End With
    MsgBox rng.Address(0, 0)
End Sub

enter image description here

关于excel - 找到被占用的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61938169/

相关文章:

vba - 为什么这条 IF-THEN 行在没有 END IF 的情况下工作?

excel - 如何快速判断一个字符串的一部分是否与另一个字符串匹配?

excel - 根据vba中单元格(查找)中可用的值执行while循环

c# - Microsoft Graph API 以 HTML 格式返回邮件正文

c# - 不知道为什么 C# PowerShell Runspace 不定期关闭

oauth-2.0 - Microsoft Graph API Authentication_MissingOrMalformed

Excel 匹配多个条件

vba - 检查某个 pdf 文件是否打开并关闭它

excel - 基于单元格颜色逐行计算

excel - 按单元格值保存 Excel 文件并保存在打开文件的当前目录中