简体   繁体   English

使用MS Word VBA宏合并表中的单元格

[英]Merge cells in table with ms word VBA macro

I want to merge in one cell with vba, but not working. 我想与vba合并在一个单元中,但不起作用。

mycode : mycode:

Sub merge()
Dim x As Integer, i As Integer
x = ActiveDocument.Tables(1).Rows.Count
    With ActiveDocument.Tables(1)
      For i = 1 To x + 1
            If .Cell(i, 2).Range.Text = "" Then
            .Cell(Row:=i, Column:=2).merge _
            MergeTo:=.Cell(Row:=i, Column:=3)
            .Borders.Enable = False
            End If      
      Next i
    End With
End Sub

In the document, I have a table (five row and three columns). 在文档中,我有一个表(五行和三列)。

For excel VBA code writers, it is a common conceptual problem, we used to treat a blank cell as empty (""). 对于excel VBA代码编写器,这是一个常见的概念性问题,我们过去将空白单元格视为空(“”)。 but actually an apparently blank Word table cell contains two invisible characters (at least in word 2007) ie chr(13) & Chr(7) . 但是实际上一个看似空白的Word表单元格包含两个不可见字符(至少在word 2007中),即chr(13)Chr(7) it could be tested with simple statement like 可以用简单的语句进行测试,例如

MsgBox Len(.Cell(1, 1).Range.Text)
MsgBox Asc(Right(.Cell(1, 1).Range.Text, 1))
MsgBox Asc(Left(.Cell(1, 1).Range.Text, 1))

so to make your code work it may be modified to something like 为了使您的代码正常工作,可以将其修改为类似

Sub merge()
Dim x As Integer, i As Integer, S As String
x = ActiveDocument.Tables(1).Rows.Count
    With ActiveDocument.Tables(1)
      For i = 1 To x
      S = .Cell(i, 2).Range.Text
      S = Replace(S, Chr(13), "")
      S = Replace(S, Chr(7), "")
            If S = "" Then
            .Cell(Row:=i, Column:=2).merge _
            MergeTo:=.Cell(Row:=i, Column:=3)
            .Borders.Enable = False
            End If
      Next i
    End With
End Sub

or test line may be modified to 或测试行可以修改为

If Len(.Cell(i, 2).Range.Text) = 2 Then

also could not understand why in your code you are iterating to ActiveDocument.Tables(1).Rows.Count+1 so for testing i used only For i = 1 To x 也无法理解为什么在您的代码中您要迭代到ActiveDocument.Tables(1).Rows.Count+1所以对于测试,我仅For i = 1 To x

Try changing: 尝试更改:

If .Cell(i, 2).Range.Text = "" Then

to: 至:

If Split(.Cell(i, 2).Range.Text,vbCr)(0) = "" Then

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM