gpt4 book ai didi

vba - 如何知道细胞是否存在

转载 作者:行者123 更新时间:2023-12-03 09:16:35 25 4
gpt4 key购买 nike

我进行了搜索,但找不到执行此操作的方法。

我想知道这是否可行

if ActiveDocument.Range.Tables(1).Cell(i, 2) present
do some stuff
end if

最佳答案

这可以工作:

Dim mycell as cell

On Error Resume Next 'If an error happens after this point, just move on like nothing happened
Set mycell = ActiveDocument.Range.Tables(1).Cell(1, 1) 'try grabbing a cell in the table
On Error GoTo 0 'If an error happens after this point, do the normal Error message thingy
If mycell Is Nothing Then 'check if we have managed to grab anything
MsgBox "no cell"
Else
MsgBox "got cell"
End If

如果您想在循环中测试多个单元格,请不要忘记在重试之前设置 mycell=nothing

(除了 mycell 变量方式,您还可以检查尝试使用单元格时是否发生错误。您可以使用 If err > 0 Then 来执行此操作。但是根据我的经验,这种方式有点不稳定。)


OP具体问题的具体答案:

If .Find.Found Then 'this is custom text search, has nothing to do with specified cell exist.
Set testcell = Nothing
On Error Resume Next
Set testcell = tbl.Cell(i, 6)
On Error GoTo 0
If Not testcell Is Nothing Then
tbl.Cell(i, 2).Merge MergeTo:=tbl.Cell(i, 3)
End If
End If

这意味着:

If your .find does whatever... then
Try grabbing the cell in question (the 4 rows: Set...Nothing, On error..., Set..., On Error...)
If we could grab the cell, then merge cells

阅读一些有关 VBA 中的错误处理(On Error 语句)的内容。在 VBA 中,没有 Try...Catch。这就是我们可以做的。

我希望这能解决问题。


作为引用,我将在此处发布完整的代码:

Sub test()

Dim tbl As Table
Dim testcell As Cell

Set tbl = ActiveDocument.Range.Tables(1)

For i = 1 To 6

Set testcell = Nothing
On Error Resume Next
Set testcell = tbl.Cell(i, 6)
On Error GoTo 0

If Not testcell Is Nothing Then
tbl.Cell(i, 2).Merge MergeTo:=tbl.Cell(i, 3)
End If

Next i

End Sub

关于vba - 如何知道细胞是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36953360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com