Excel:vba实现批量插入图片批注

实现的效果:

实现的代码如下:

复制代码
Sub InsertImageNamesAndPictures()
    Dim PicPath As String
    Dim PicName As String
    Dim PicFullPath As String
    Dim RowNum As Integer
    Dim Name As String
    Dim Comment As Comment
    Dim folder As FileDialog '定义文件选择对话框
    
    ' 清空单元格中的内容和图片,防止有脏数据
    Cells.Clear
    For Each Pic In ActiveSheet.Pictures
        Pic.Delete
    Next Pic
    
    '忽略出现的错误,继续执行后面的代码,假如这个图片不存在或者有所损坏,会继续执行下个图片的插入
    On Error Resume Next

    ' 设置你的图片文件夹路径(两种获取文件路径的方法)
    'PicPath = "C:\Users\HUAWEI\Pictures\Screenshots\"
    
    '上面的是直接写出文件路径,下面的是动态的选择选择路径
    'set folder创建并设置一个文件夹选择对话框
    Set folder = Application.FileDialog(msoFileDialogFolderPicker)
    '这里等于-1是用户选择并点击"确定"了文件夹,如果用户点击取消没有选择文件夹,就会返回0
    If folder.Show = -1 Then
        'folder.SelectedItems(1)返回了文件夹的路径,只不过最后没有\。PicPath是图片路径,最后加上\
        PicPath = folder.SelectedItems(1) & "\"
    Else
        MsgBox "未选择文件夹,程序结束"
        Exit Sub
    End If
    

    ' 初始化行号
    RowNum = 1

    ' 获取文件夹中的第一个文件名
    PicName = Dir(PicPath & "*.*")

    ' 遍历所有图片文件
    Do While PicName <> ""
        ' 去掉文件扩展名
        Name = Left(PicName, InStrRev(PicName, ".") - 1)
        ' 将文件名插入到 A 列
        Cells(RowNum, 1).value = Name

        ' 拼接完整路径
        PicFullPath = PicPath & PicName

        ' 在 A 列单元格添加批注
        Set Comment = Cells(RowNum, 1).AddComment
        Comment.Text Text:=" "  ' 必须有一些文本

        ' 插入图片到批注中
        With Comment.Shape
            .Fill.UserPicture PicFullPath  ' 设置图片作为批注的背景
            .Width = 50  ' 设置图片宽度
            .Height = 50 ' 设置图片高度
        End With

        ' 设置行高(可以根据需要调整)
        Rows(RowNum).RowHeight = 50

        ' 移动到下一行
        RowNum = RowNum + 1

        ' 获取下一个文件名
        PicName = Dir
    Loop
End Sub

实现删除批注:

相关推荐
一晌小贪欢14 小时前
python-第15天:Python 列表推导式
开发语言·python·excel·数据可视化·python办公
tryxr19 小时前
Chat2Excel 项目通用服务开发
java·开发语言·excel·java项目开发
Jazz_z19 小时前
使用 Python 合并与取消合并 Excel 单元格
开发语言·python·excel
2601_962381862 天前
Python办公联动:Excel数据一键自动生成PPT图表
python·数据分析·自动化·excel·ppt
tryCbest4 天前
Excel常用公式(WPS vs Office)
excel·wps
taller_20004 天前
【006】何时用 Python?何时用 Excel 公式?一文讲清
python·excel·公式·pie·py
2601_949950634 天前
Word、PDF、Excel题目怎么快速整理?
pdf·word·excel
Eiceblue4 天前
React 项目实战:用 JavaScript 合并多个本地 Excel 文件
前端·javascript·react.js·excel
ms365copilot5 天前
Excel做完≠结束,Copilot一键生成汇报PPT
powerpoint·excel·copilot
城数派6 天前
1901-2025年中国省市县三级逐年平均气温数据集(Shp/Excel 格式)
excel