确定ActiveCell是否在特定表中

时间:2015-12-03 21:31:12

标签: excel vba excel-vba

我试图通过VBA在Excel 2013中确定ActiveCell是否不仅存在于任何表中,而是存在于特定表中。

下面是代码,但只检测任何表中的ActiveCell。注释掉的线是我正在寻找的,但显​​然它不起作用。

    ...
    Set rng = Intersect(.EntireRow, ActiveCell.ListObject.DataBodyRange)
    'Set rng = Intersect(.EntireRow, ActiveCell.ListObjects("myTable").DataBodyRange)
    On Error GoTo 0
        If rng Is Nothing Then
            MsgBox "Please select the cell of a row within the consensus input table.", vbCritical, "Delete Evaluator"
        Else
    ...

关于正确语法的任何建议吗?

谢谢!

3 个答案:

答案 0 :(得分:7)

测试 ActiveCell 是否在 Table1 的正文中:

var html = document.getElementsByTagName('html')[0].outerHTML;

答案 1 :(得分:2)

更通用的解决方案,适用于其他表格

Sub Demo()
    Dim r As Range
    Dim lo As ListObject

    Set r = ActiveCell
    Set lo = r.ListObject
    If Not lo Is Nothing Then
        Select Case lo.Name
            Case "Table1"
                If r.Row = lo.Range.Row Then
                    MsgBox "In Table1 Header"
                Else
                    MsgBox "In Table1 Body"
                End If
            Case "SomeOtherTable"
                '...
        End Select
    Else
        MsgBox "Not in any table"
    End If
End Sub

答案 2 :(得分:0)

通常,我们对在表的DataBodyRange中执行的工作感兴趣,Excel为我们提供了表的该区域的快捷方式。对于名为“myTable”的表,您可以使用(function () { var templateEngine = new ko.nativeTemplateEngine(); ko.bindingHandlers.customPopover = { init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { var placement = allBindings.get("placement") || "top", trigger = allBindings.get("trigger") || "click", templateName = allBindings.get("customPopover") || null, $element = $(element); $element.popover({ placement: placement, trigger: trigger, html: true, content: " " }); $element.on("inserted.bs.popover", function () { var container = $element.next().find(".popover-content")[0]; if (templateName) { ko.renderTemplate(templateName, viewModel, { templateEngine: templateEngine }, container); } else { container.innerHTML = $element.attr("data-content"); } }); ko.utils.domNodeDisposal.addDisposeCallback(element, function () { $element.popover("destroy"); }); } }; })(); var model = { linkText: "Click me!", innerText: "Some fancy text" }; ko.applyBindings(model);直接访问代码中的DataBodyRange。

因此,对于ActiveCell的包容性表位置测试,可以测试如下:

<link href="https://cdn.jsdelivr.net/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<a data-bind="text: linkText, customPopover: 'popover-template', trigger: 'focus', placement: 'bottom'" tabindex="0" role="button"></a>

<script type="text/html" id="popover-template">
  <span data-bind="text: innerText"></span>
</script>