vba - 使用 VBA moodule 批量加载图像以访问数据库
问题描述
我正在尝试运行我在网上找到的东西(参见下面的代码块)。
我收到错误消息:
编译错误:找不到方法或数据成员”,它突出显示 .LoadFromFile
关于为什么卡在这里的任何想法?
Public Sub OneTimeImport()
Dim strPath As String
strPath = "myfilepath"
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject") 'this avoids adding the reference to this - but you loose the easier to write code stuff
Dim con As ADODB.Connection
Dim rs As New ADODB.Recordset
Set con = CurrentDb.Connection 'this part might need some adjustment
rs.Open "SELECT * FROM dbo_Bor_spr_Surface_Master"
If Not rs.EOF Then
Do While Not rs.EOF
If fs.FileExists(strPath & "\" & rs("Seed_ID") & ".jpg") Then
rs("Photo").LoadFromFile strPath & "\" & rs("Seed_ID")
rs.Update
End If
rs.MoveNext
Loop
End If
rs.Close
con.Close
Set rs = Nothing
Set con = Nothing
Set fs = Nothing
End Sub
解决方案
由于 ADO(ActiveX 数据对象)记录字段没有 .LoadFromFile() 方法,因此您有错误。但是 DAO (Data Access Objects) 记录 field2 有这个方法。因此,我们将您的代码修改为这样(在 Microsoft Access 2019 Pro 下测试的代码):
'
' strPath: directory path for photos
' fs: file system object
' rs: DAO.recordset
' rs2: DAO.recordset 2
'
Sub OneTimeImport()
Dim strPath As String
Dim fs As Object
'this avoids adding the reference to this - but you loose the easier to write code stuff
Set fs = CreateObject("Scripting.FileSystemObject")
'
'Dim con As ADODB.Connection
'Dim rs As New ADODB.Recordset
'
Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
strPath = "myfilepath"
'Set con = CurrentDb.Connection 'this part might need some adjustment
Set rs = CurrentDb.OpenRecordset("SELECT * FROM dbo_Bor_spr_Surface_Master")
'
Do While Not rs.EOF
'
If fs.FileExists(strPath & "\" & rs("Seed_ID") & ".jpg") Then
'
' edit the main record:
'
rs.Edit
'
' make a sub-record:
'
Set rs2 = rs("Photo").Value
rs2.AddNew
rs2("FileData").LoadFromFile strPath & "\" & rs("Seed_ID") & ".jpg"
rs2.Update
rs2.Close
'
rs.Update
End If
'
rs.MoveNext
'
Loop
'
' clear memory:
'
Set rs2 = Nothing
rs.Close
Set rs = Nothing
Set fs = Nothing
End Sub
要使用它,照片列必须是访问“附件数据类型”,参考。https://support.microsoft.com/en-us/office/attach-files-and-graphics-to-the-records-in-your-database-d40a09ad-a753-4a14-9161-7f15baad6dbd
推荐阅读
- c# - EF Core 代码优先创建数据库,但无处可见
- azure - 在创建新的 AzureMediaServicesClient 时尝试将元素作为与数组不兼容的类型进行访问
- azure - 使用 Mongo 连接到运行 Docker 的 Azure Cosmos DB 模拟器失败
- powershell - 如何使用 PowerShell 导出包含特定电子邮件域的 csv 文件中的行?
- arrays - 谷歌表格数组公式,用于将带逗号的单元格拆分和转置到另一列中
- java - Spring CannotGetJdbcConnectionException,嵌套异常 jdbc4.MySQLNonTransientConnectionException
- kubernetes - Kubernetes 1.16 Nginx Ingress (0.26.1) TCP Mariadb/MySQL 服务不工作
- math - 无递归的浮点幂函数
- javascript - 如何从我的 NodeJS Web 应用程序的前端 JS 文件中的函数发送 POST 请求?
- gradle - Gradle依赖,在项目中用在什么地方