基于AutoCAD VBA实现复制数字自加一
1、启动CAD VBA
2、插入模块
3、代码如下
Private Sub AcadDocument_BeginCommand(ByVal CommandName As String)
' 监听复制命令触发
If UCase(CommandName) = "COPYCLIP" Or UCase(CommandName) = "COPY" Then
Call CopyTextAddNumber
ThisDrawing.SendCommand "_cancel" & vbCr
End If
End Sub
Sub CopyTextAddNumber() Dim ent As AcadEntity Dim txtObj As AcadText Dim basePt As Variant Dim insertPt As Variant Dim txtStr As String Dim newTxtStr As String Dim i As Integer, numStart As Integer Dim num As Integer Dim prefix As String, numStr As String
' 选择源文字
On Error Resume Next
ThisDrawing.Utility.GetEntity ent, basePt, "请选择递增复制的单行文字:"
If Err.Number <> 0 Then Exit Sub
On Error GoTo 0
If Not TypeOf ent Is AcadText Then
**MsgBox "仅支持单行文字!"**
Exit Sub
End If
Set txtObj = ent
' 解析尾部数字
txtStr = txtObj.TextString
numStart = 0
For i = Len(txtStr) To 1 Step -1
If IsNumeric(Mid(txtStr, i, 1)) Then
numStart = i
Else
Exit For
End If
Next
If numStart = 0 Then
MsgBox "文字末尾无递增数字!"
Exit Sub
End If
prefix = Left(txtStr, numStart - 1)
numStr = Mid(txtStr, numStart)
num = CInt(numStr)
' 拾取复制基点(可正常捕捉)
On Error Resume Next
basePt = ThisDrawing.Utility.GetPoint(, "指定复制基点:")
If Err.Number <> 0 Then Exit Sub
On Error GoTo 0
' 连续指定目标点,支持捕捉,每点一次序号+1
Do
On Error Resume Next
insertPt = ThisDrawing.Utility.GetPoint(basePt, "指定放置目标点(ESC退出):")
If Err.Number <> 0 Then Exit Do ' ESC退出
On Error GoTo 0
num = num + 1
newTxtStr = prefix & Format(num, String(Len(numStr), "0"))
' 按拾取坐标生成文字
Dim newTxt As AcadText
Set newTxt = ThisDrawing.ModelSpace.AddText(newTxtStr, insertPt, txtObj.Height)
newTxt.StyleName = txtObj.StyleName
newTxt.Rotation = txtObj.Rotation
newTxt.color = txtObj.color
Loop
ThisDrawing.Regen acActiveViewport
End Sub 4、测试