如何知道细胞是否存在

问题描述 投票:1回答:2

我搜索但找不到这样做的方法。

我想知道这是否可行

if ActiveDocument.Range.Tables(1).Cell(i, 2) present
  do some stuff
end if
vba ms-word word-vba
2个回答
3
投票

这可以工作:

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

如果你想在一个循环中测试多个单元格,在再次尝试之前不要忘记set 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

1
投票

将解决方案作为参考函数发布...

Function cellExists(t As table, i As Integer, j As Integer) As Boolean
  On Error Resume Next
  Dim c As cell
  Set c = t.cell(i, j)
  On Error GoTo 0
  cellExists = Not c Is Nothing
End Function
© www.soinside.com 2019 - 2024. All rights reserved.