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

实现删除批注:

相关推荐
LAM LAB9 天前
【VBA】Excel指定单元格范围内字体设置样式,处理导出课表单元格
excel·vba
在这habit之下9 天前
Keepalived学习总结
excel
Youngchatgpt9 天前
如何在 Excel 中使用 ChatGPT:自动化任务和编写公式
人工智能·chatgpt·自动化·excel
开开心心就好10 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
D_C_tyu10 天前
Vue3 + Element Plus | el-table 多级表头表格导出 Excel(含合并单元格、单元格居中)第二版
vue.js·elementui·excel
骆驼爱记录10 天前
WPS页码设置:第X页共Y-1页
自动化·word·excel·wps·新人首发
Cxiaomu11 天前
Python 文件解析: Excel / Word / PDF 的解析、处理、预览与下载
python·word·excel
2501_9307077811 天前
如何使用C#代码从 PDF 中提取表格并另存为Excel文件
pdf·excel
pacong11 天前
B生所学EXCEL
人工智能·excel