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

标签 vba ms-word

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

我想知道这是否可行

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/

相关文章:

vba - 你如何让一个变量成为你的事件单元格?

vba - 如何从Excel中的一列数据中删除一个字符

excel - 将多行文本单元格从 Word 表复制到 Excel 单元格

excel - VBA从数据验证列表创建文件夹并允许用户选择文件夹

vba - 运行时错误 '1004' 未找到单元格错误

c# - 从数据库中打开 word 文档(保存为二进制文件)

ms-word - 我们可以使用 Office 365 API 来操作 word 文档,转换成 pdf 等吗

vba - 如何将Word文档中的所有表格导出到单独的Excel工作表

vba - 更改图像大小

python - 使用 python 创建 word 文件 (.doc)