这个程序代码:
Option Compare Text '以文本方式比较
Sub AutoFormula()
Dim aCell As Cell, Fct As String, Rfct As String, StartRow As Integer, EndRow As Integer
Dim StartCol As Byte, EndCol As Byte, i As Byte
On Error Resume Next
Application.ScreenUpdating = False
With Selection
If .Information(wdWithInTable) = False Then MsgBox "光标未处于Word表格中!": GoTo 10
StartRow = .Cells(1).RowIndex
EndRow = .Cells(.Cells.Count).RowIndex
StartCol = .Cells(1).ColumnIndex
EndCol = .Cells(.Cells.Count).ColumnIndex
Fct = InputBox("请输入选定单元格中首个单元格的公式,以=开头! 注意引用单元格的行(列)号与公式中的引用相一致!")
If Fct Like "=[a-z]#*" = False Or Fct = "" Then MsgBox "无效公式!": GoTo 10
If StartCol = EndCol Then
For Each aCell In .Cells
If aCell.RowIndex = StartRow Then
aCell.Formula Formula:=Fct
Else
Rfct = Replace(Fct, StartRow, aCell.RowIndex)
aCell.Formula Formula:=Rfct
End If
Next
ElseIf StartRow = EndRow Then
.Tables(1).Cell(StartRow, StartCol).Select
.InsertFormula Formula:=Fct
For i = StartCol + 1 To EndCol
Rfct = Replace(Fct, Chr(StartCol + 96), Chr(i + 96))
.MoveRight unit:=wdCell
.InsertFormula Formula:=Rfct
Next
Else
MsgBox "多行多列的单元格选定区域,Word不予支持!"
End If
End With
10: Exit Sub
Application.ScreenUpdating = True
End Sub
这是程序注释:
Option Compare Text '以文本方式比较
Sub AutoFormula()
Dim aCell As Cell, Fct As String, Rfct As String, StartRow As Integer, EndRow As Integer
Dim StartCol As Byte, EndCol As Byte, i As Byte
On Error Resume Next'错误处理(忽略错误)
Application.ScreenUpdating = False'关闭屏幕刷新
With Selection
If .Information(wdWithInTable) = False Then MsgBox "光标未处于Word表格中!": GoTo 10'检测选定部分或者单元格是否处于表格中
StartRow = .Cells(1).RowIndex'选定单元格的开始行号
EndRow = .Cells(.Cells.Count).RowIndex'选定单元格的开始列号
StartCol = .Cells(1).ColumnIndex'选定单元格的结束行号
EndCol = .Cells(.Cells.Count).ColumnIndex'选定单元格的结束列号
Fct = InputBox("请输入选定单元格中首个单元格的公式,以=开头! 注意引用单元格的行(列)号与公式中的引用相一致!")
'初步判断公式录入是否正确,如果不正确转入行标签为10的语句
If Fct Like "=[a-z]#*" = False Or Fct = "" Then MsgBox "无效公式!": GoTo 10
If StartCol = EndCol Then'判断是否为同一行中的选定单元格
For Each aCell In .Cells
If aCell.RowIndex = StartRow Then
aCell.Formula Formula:=Fct'填充第一个公式
Else
Rfct = Replace(Fct, StartRow, aCell.RowIndex)
aCell.Formula Formula:=Rfct'根据列号循环填充公式
End If
Next
ElseIf StartRow = EndRow Then'判断是否为同一列中的选定单元格
.Tables(1).Cell(StartRow, StartCol).Select
.InsertFormula Formula:=Fct'填充第一个单元格公式
For i = StartCol + 1 To EndCol
Rfct = Replace(Fct, Chr(StartCol + 96), Chr(i + 96))
.MoveRight unit:=wdCell
.InsertFormula Formula:=Rfct'循环填充公式(将行号与字母转换)
Next
Else
MsgBox "多行多列的单元格选定区域,Word不予支持!"
End If
End With
10: Exit Sub
Application.ScreenUpdating = True'恢复屏幕刷新
End Sub
'后记,细心的大家也许会发现为什么第一个循环与第二个循环不一致,以及上次的一篇贴子中我也谈到的有些电脑上不能通过,经笔者反复试验,当所一个同行单元格中的公式域的BUG.
有兴趣的朋友可以试一下这个代码:(选中某一行)
Sub CheckBug()
Dim i As Cell
For Each i In Selection.Cells
i.Formula Formula:="=123"
Next
End Sub
这是所有图释:
iIf50Nzk.zip
(27.73 KB, 下载次数: 71)
代码请自行复制并测试!
|