我搜索但找不到这样做的方法。
我想知道这是否可能
if ActiveDocument.Range.Tables(1).Cell(i, 2) present
do some stuff
end if
答案 0 :(得分: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 :(得分: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