PAYATHON 2026

VBA Word:根据文件名代码生成照片题注

数据小陈

把 InsertCaption 的 Label 从 Table 改成 Figure,并把 Title 改为 ": " & CaptionTextFromFile(fileName)。Word 就会生成 Figure 1: 这类自动编号,冒号后面的说明由文件名解析得到。不要手写死 Figure 1,否则插入多张图片或后续增删图片时编号容易出错。

原代码里写的是 Label:="Table",所以生成出来就是 Table 题注;Title 又直接用了 fileName。像 SP_01_BH03.jpg 这样的文件名,要先去掉扩展名,再按 _ 拆分;SP 对应 Stockpile,BH 对应 Borehole,数字保持原样。下面的函数同时兼容 BH03 和 BH_03 两种写法。

修改步骤:

  1. 保留原来的插入图片、缩放和换行逻辑。
  2. 在模块中加入 CaptionTextFromFile、AlphaPrefix、MapCode 三个函数。
  3. 用下面的调用替换原来的 img.Range.InsertCaption ...。
' 替换原题注调用
img.Range.InsertCaption _
    Label:="Figure", _
    Title:=": " & CaptionTextFromFile(fileName), _
    Position:=wdCaptionPositionBelow

' 放到同一个模块中
Private Function CaptionTextFromFile(ByVal fileName As String) As String
    Dim baseName As String
    Dim p As Long
    Dim parts() As String
    Dim i As Long
    Dim token As String
    Dim code As String
    Dim num As String
    Dim nextPart As String
    Dim result As String

    p = InStrRev(fileName, ".")
    If p > 0 Then
        baseName = Left$(fileName, p - 1)
    Else
        baseName = fileName
    End If

    parts = Split(baseName, "_")
    For i = LBound(parts) To UBound(parts)
        token = parts(i)
        If Len(token) > 0 Then
            code = AlphaPrefix(token)
            num = Mid$(token, Len(code) + 1)

            If Len(num) = 0 And i < UBound(parts) Then
                nextPart = parts(i + 1)
                If IsNumeric(nextPart) Then
                    num = nextPart
                    i = i + 1
                End If
            End If

            If Len(code) > 0 Then
                result = Trim$(result & " " & MapCode(code))
                If Len(num) > 0 Then result = result & " " & num
            Else
                result = Trim$(result & " " & token)
            End If
        End If
    Next i

    CaptionTextFromFile = result
End Function

Private Function AlphaPrefix(ByVal s As String) As String
    Dim i As Long
    For i = 1 To Len(s)
        If Not Mid$(s, i, 1) Like "[A-Za-z]" Then Exit For
    Next i
    AlphaPrefix = Left$(s, i - 1)
End Function

Private Function MapCode(ByVal code As String) As String
    Select Case UCase$(code)
        Case "SP": MapCode = "Stockpile"
        Case "BH": MapCode = "Borehole"
        Case Else: MapCode = code
    End Select
End Function

注意事项:

  • fileName 在 Dir 循环里只是文件名,不含路径;函数还会去掉扩展名,所以不会把 .jpg 带进题注。
  • 如果文件名里还有更多代码,在 MapCode 里继续加 Case 即可;未识别的代码会原样保留。
  • Label:="Figure" 要求当前 Word 的题注标签里有 Figure。如果界面是本地化版本且标签名不同,把 Label 改成实际存在的标签名,或者先通过“引用→插入题注”新建 Figure 标签。
  • 若图片插入后题注位置不理想,先检查 Position:=wdCaptionPositionBelow 和图片所在段落,不要靠硬编码编号来修。

备注:内容仅供参考。