You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Microsoft Access中将文件尺寸信息保存至数据表?

Access VBA 获取图片尺寸存入数据表解决方案

你当前使用的 Scripting.FileSystemObject 组件的 File 对象不存在 Dimensions 属性,无法直接读取图片宽高参数,可借助Windows系统自带的WIA(Windows图像获取)组件实现该需求,修改后的代码如下:

Option Explicit
Sub ListFiles()
    Dim Counter As Integer
    Dim myObject As Scripting.FileSystemObject
    Dim MySource As Scripting.Folder
    Dim MyFile As Scripting.File
    Dim db As Database
    Dim rst As Recordset
    Dim mysql As String
    ' 图片读取相关变量
    Dim imgObj As Object
    Dim fileDimStr As String
    
    Set myObject = New Scripting.FileSystemObject
    Set MySource = myObject.GetFolder("X:\I m A g E - F o L d E r\Website\Brochure Images & PDF\")
    
    ' 清空原有数据,修正原代码的语法空格问题
    DoCmd.RunSQL "DELETE * FROM tblPDFs"
 
    Set db = CurrentDb()
    mysql = "tblPDFs"
    Set rst = db.OpenRecordset(mysql, dbOpenDynaset)
      
    For Each MyFile In MySource.Files
        fileDimStr = ""
        ' 判断是否为常见图片格式,可根据需求增删后缀
        Select Case LCase(Mid(MyFile.Name, InStrRev(MyFile.Name, ".") + 1))
            Case "jpg", "jpeg", "png", "gif", "bmp"
                ' 调用WIA组件读取图片尺寸
                On Error Resume Next
                Set imgObj = CreateObject("WIA.ImageFile")
                imgObj.LoadFile MyFile.Path
                If Err.Number = 0 Then
                    fileDimStr = imgObj.Width & "×" & imgObj.Height & " 像素"
                End If
                Err.Clear
                Set imgObj = Nothing
                On Error GoTo 0
        End Select
        
        ' 写入数据表
        rst.AddNew
        rst![FilePath] = MyFile.Path
        rst![FileName] = MyFile.Name
        rst![FileDim] = fileDimStr
        rst![FileType] = MyFile.Type
        rst.Update
          
        Counter = Counter + 1
    Next
          
    ' 清理资源
    rst.Close
    db.Close
    Set rst = Nothing
    Set db = Nothing
    Set myObject = Nothing
    Set MySource = Nothing
     
    MsgBox "已列出 " & Counter & " 个文件。"
End Sub

补充说明

  • 代码采用迟绑定方式调用WIA组件,无需手动添加VBA引用,兼容性更强
  • 内置错误捕获逻辑,损坏的图片、非图片类文件不会导致代码运行中断,对应FileDim字段会自动留空
  • 若需要读取PDF文件的尺寸,可额外接入PDF解析组件调整逻辑即可

内容的提问来源于stack exchange,提问作者Stuarts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:06:05