word、wps中使用vba删除所有表格指定列

word、wps中使用vba删除所有表格指定列


处理word表格搞得人头大,找时间百度一波写了个函数处理标记删除的问题,根据这一套逻辑还可以实现很多功能,供各位参考。

要点:
双循环遍历所有表表头
InStr函数匹配具体内容(word表格多半有特殊字符,相等匹配较难保证)
在内循环结束后进行删除,否则将出错

用法:
1、定义条件,如 InStr(value1, “学号”),多条件拼接(如 InStr(value1, “学号”)>0 or InStr(value1, “姓名”) >0)
2、新建宏名range,粘贴内容到vba编辑器
3、执行

效果:
在这里插入图片描述

代码:



'ver 2.0

Sub range()
'遍历文档所有表格,删除表头第一行含有特定字符串的列
Dim value1 As String
Dim target() As Integer
For i = 1 To ActiveDocument.Tables.Count
  Dim targetLen As Integer
  targetLen = 0
  For j = 1 To ActiveDocument.Tables(i).Columns.Count
     value1 = ActiveDocument.Tables(i).Columns(j).Cells(1).range.Text
     '这里定义条件,可以定义多个条件
     If InStr(value1, "测试") > 0 or InStr(value1, "学号") > 0 Then
     targetLen = targetLen + 1
     ReDim Preserve target(targetLen)
     target(targetLen - 1) = j
     Else
     End If
  Next j
  If targetLen <> 0 Then
  ' MsgBox targetLen
    ' 修正删除操作带来的列号偏移
   Dim shift As Integer
   shift = 0
   For k = 0 To (targetLen - 1)
     ' MsgBox target(k)
       ActiveDocument.Tables(i).Columns(target(k) - shift).Delete
       shift = shift + 1
    Next k
  End If
Next i
    MsgBox ("执行完毕。")
End Sub

使用过程中遇到复合表格遍历报错问题,修改加入错误处理跳过
(注意,因需求变动这里已经改成了匹配第一列,如仍需匹配第一行,请按上一段代码循环条件设置)

'ver 3.0
Dim value1 As String
Dim target() As Integer
For i = 1 To ActiveDocument.Tables.Count
  'MsgBox ("遍历表 " & i & "。")
  Dim targetLen As Integer
  targetLen = 0
  For j = 1 To ActiveDocument.Tables(i).Rows.Count
     On Error GoTo flag
     value1 = ActiveDocument.Tables(i).Rows(j).Cells(1).range.Text
     '这里定义条件
     If InStr(value1, "test1") > 0 Or InStr(value1, "test2") > 0  Then
     targetLen = targetLen + 1
     ReDim Preserve target(targetLen)
     target(targetLen - 1) = j
     Else
     End If
  Next j
  If targetLen <> 0 Then
  ' MsgBox targetLen
    ' 修正删除操作带来的列号偏移
   Dim shift As Integer
   shift = 0
   For k = 0 To (targetLen - 1)
     ' MsgBox target(k)
       ActiveDocument.Tables(i).Rows(target(k) - shift).Delete
       shift = shift + 1
    Next k
  End If
flag:
    Resume continue
continue:
Next i
    MsgBox ("执行完毕。")
End Sub

如需删除而非跳过复合行,则删除代码需换成下列实现形式

 With ActiveDocument
        .Tables(1).Cell(2, 2).Delete ShiftCells:=wdDeleteCellsEntireRow
    End With
  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值