如何从文件创建 ole 对象 - Ms-access

发布于 2024-11-14 22:31:29 字数 1199 浏览 2 评论 0原文

我有一张带有嵌入图片(OLE)的表格。

我希望能够通过带有浏览选项的表单插入新记录。

不管怎样,我有一个文件名,我需要将它变成一个ole对象并将其插入到表单中。我如何在 VBA 中做到这一点?

澄清一下 - 我需要将文件名转换为该文件的 ole 对象,然后将其插入表中。

谢谢, 手指曼。

编辑:

好的,正如@HansUp 所指出的,我需要解释一下。 在我的表单中,我有一个绑定的 OLE 对象,该对象未绑定到字段,而是绑定到 dlookup 函数。我通过查询和组合框将正确的 ID 获取到控件中 - 因此控制器绑定到:

=DLookUp("picture","articles","id=" & [articles])

请注意,文章不是字段,而是控制器,我不知道这是否有任何区别。

每次更改控制器时,我都会使用 me.recalc 以便绑定的 OLE 可以更新其值。

无论如何,我想仅通过 VBA 和用户输入文件地址来完成此操作,而不使用控制器,而是使用某种 INSERT 或其他东西,但欢迎其他选项。

如果我不清楚,请询问!我会澄清并修复自己。

编辑2:

那么文件名是如何获取的或者 衍生的?您是否期望使用 文章ID?图片是否始终处于 预期位置与预期 文件名?你到底想要什么 如果不使用浏览按钮怎么办? 你正在寻找完全的东西吗 基于文件夹和文件自动化 名字或者你在寻找什么 像拖放一样?

文件名是通过浏览选项获取的,我已经实现了。为了简单起见 - 假设用户必须自己将文件名输入到文本框中。 现在 - 我希望只需单击一个按钮,我就可以将该文件名作为嵌入式 ole 对象插入到我的数据库中。我不是在寻找任何自动化,也不是拖放(但是,如果拖放有效,那就太好了)。自从有人问以来,第一次编辑是关于 ole 控制器的。他认为我的问题可以使用该控制器来解决 - 所以我详细说明了如何显示图片。我不认为它有任何相关性,但如果有人可以使用它,那对我来说就很好了。我希望使用 ArticleID 进行更新 - 但同样,我不明白这与问题有何关系。

我开始认为这可能是不可能的......:( 这是不幸的,因为这个问题相当简单。 您有一个文件名,您需要将其作为 OLE 对象嵌入到数据库中。

I have a table with an embedded picture(OLE) coulmn.

I Want to be able to insert a new record via a form with a browse option.

Anyway, I have a file name, And I need to turn it into an ole object and insert it into the form. how do I do that in VBA?

To clarify - I need to turn a file name, into an ole object with that file, and than insert it into the table.

Thanks,
Fingerman.

EDIT:

Ok, as pointed out by @HansUp I need to explain.
In my form, I have a bound OLE object that is not bound to a field, but to a dlookup function. I get the correct id into a controll via a query and a combo box - so the controller is bound to:

=DLookUp("picture","articles","id=" & [articles])

note that articles is not a field but a controller, I don't know if that does any diffrence.

Every time that controller is changed I use me.recalc so that the bound OLE may update it's value.

Anyway, I thought to do this just by VBA and a user entering a file adress,without using the controller but some kind of INSERT or somthing, but other options would be welcome.

If I am not clear, ASK! I will clarify and fix myself.

EDIT 2:

So how is the filename acquired or
derived? Are you expecting to use the
ArticleID? Is the picture always at an
expected location with an expected
file name? What exactly do you want to
do if you don't use the Browse button?
Are you looking for something fully
automated based on the folder and file
name or are you looking for something
like drag and drop?

the filename is aquired via a browse option, I have it implented. for the sake of simplicty - let's say the user has to enter the file name themselves to a text box.
now - I want that on a click of a button, I could insert that file name as an embedded ole object - to my database. I'm not looking for any automation nor drag and drop (But, If drag & drop works, It would be great). The first edit is about the ole controller since someone asked. he thought my question could be resolved using that controller - so I gave details on how I am desplaying the picture. I don't think it has any relevance but If someone could use that, it would be fine by me. I am expecting to use an articleID for the update - but again, I don't see how this relates to the question.

I am beginning to think this might be not possible..... :(
This is unfortunte since the porblem is fairly stright-forward. you have a file-name, you need it embeeded as an OLE object in your database.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉南桥 2024-11-21 22:31:29

在提供答案之前,我将快速浏览一下您的问题及其要求。在我看来,您希望能够使用 VBA、表中的 OLE 对象字段和绑定对象框架加载二进制文件对象(在本例中为图片)。

您最好的选择是停止尝试使用绑定对象框架,因为它有太多限制。

对于您想要做的事情,基本上有两种推荐的方法。

1)仅存储图像文件的链接,然后使用图像控件(可以将其绑定到您的图片字段)来显示图像。

2) 使用代码将图像存储在 OLE 对象字段中,以将图像作为二进制数据读取。当需要显示图像时,需要将其写入临时文件,然后可以将图像控件上的 Picture 属性设置为临时图像文件的完整路径和文件名。您可以将图像文件作为临时文件进行管理。您可以使用 Windows 的临时目录,也可以在每次需要显示图像时简单地写入相同的文件名。

这些技术都不是太困难。这里有一篇非常好的文章可以帮助您进一步理解我在说什么:http://www .jamiessoftware.tk/articles/handlingimages.html

这是一个读取二进制数据(在本例中为图片文件)的函数和另一个写出二进制数据的函数:http://www.ammara.com/access_image_faq/read_write_blob.html 这非常适合编写您的图片输出到“临时”文件。然后您所要做的就是将图像控件上的 Picture 属性设置为临时文件的文件路径和名称。

您还可以使用 ADO Stream 对象以及 ADO RecordSet 对象和 ADO Connection 对象来读取和写入二进制数据。您必须在 Access to Microsoft ActiveX Data Objects 2.8 Library 中设置引用。

以下是使用 ADO 将图片添加到数据库的一些代码:

Private Function LoadPicIntoDatabase(sFilePathAndName As String) As Boolean
On Error GoTo ErrHandler

    'Test to see if the file exists. Exit if it does not.
    If Dir(sFilePathAndName) = "" Then Exit Function

    LoadPicIntoDatabase = True

    'Create a connection object
    Dim cn As ADODB.Connection
    Set cn = CurrentProject.Connection

    'Create our other variables
    Dim rs As ADODB.Recordset
    Dim mstream As ADODB.Stream
    Set rs = New ADODB.Recordset

    'Configure our recordset variable and open only 1 record (if one exists)
    With rs
        .LockType = adLockOptimistic
        .CursorLocation = adUseClient
        .CursorType = adOpenDynamic
        .Open "SELECT TOP 1 * FROM tblArticles", cn
    End With

    'Open our Binary Stream object and load our file into it
    Set mstream = New ADODB.Stream
    mstream.Open
    mstream.Type = adTypeBinary
    mstream.LoadFromFile sFilePathAndName

    'add a new record and read our binary file into the OLE Field
    rs.AddNew
    rs.Fields("olepicturefield") = mstream.Read
    rs.Update

    'Edit: Removed some cleanup code I had inadvertently left here.


Cleanup:
    On Error Resume Next
    rs.Close
    mstream.Close
    Set mstream = Nothing
    Set rs = Nothing
    Set cn = Nothing

    Exit Function

ErrHandler:
    MsgBox "Error: " & Err.Number & " " & Err.Description
    LoadPicIntoDatabase = False
    Resume Cleanup

End Function


Private Sub Command0_Click()
    If IsNull(Me.txtFilePathAndName) = False Then
        If Dir(Me.txtFilePathAndName) <> "" Then
            If LoadPicIntoDatabase(Me.txtFilePathAndName) = True Then
                MsgBox Me.txtFilePathAndName & " was successfully loaded into the database."
            End If
        End If
    End If
End Sub

Edit1:

根据您的请求,以下是用于查找/加载给定文章的图片的代码。为了保持一致性,我还更改了上面的表和字段名称,以更好地反映您的项目并匹配下面的代码。我测试了这段代码,它对我来说工作正常。

Private Sub Command1_Click()
    If IsNull(Me.txtArticleID) = False Then
        If DCount("articleid", "tblArticles", "articleid = " & Me.txtArticleID) = 1 Then
            Dim rs As DAO.Recordset, sSQL As String, sTempPicture As String
            sSQL = "SELECT * FROM tblArticles WHERE ArticleID = " & Me.txtArticleID
            Set rs = CurrentDb.OpenRecordset(sSQL)
            If Not (rs.EOF And rs.BOF) Then
                sTempPicture = "C:\MyTempPicture.jpg"
                Call BlobToFile(sTempPicture, rs("olepicturefield"))
                If Dir(sTempPicture) <> "" Then
                    Me.imagecontrol1.Picture = sTempPicture
                End If
            End If
            rs.Close
            Set rs = Nothing
        Else
            MsgBox "Article Not Found"
        End If
    Else
        MsgBox "Please enter an article id"
    End If
End Sub

Private Function BlobToFile(strFile As String, ByRef Field As Object) As Long
    On Error GoTo BlobToFileError

    Dim nFileNum As Integer
    Dim abytData() As Byte
    BlobToFile = 0
    nFileNum = FreeFile
    Open strFile For Binary Access Write As nFileNum
    abytData = Field
    Put #nFileNum, , abytData
    BlobToFile = LOF(nFileNum)

BlobToFileExit:
    If nFileNum > 0 Then Close nFileNum
    Exit Function

BlobToFileError:
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, _
           "Error writing file in BlobToFile"
    BlobToFile = 0
    Resume BlobToFileExit

End Function        

Before providing my answers, I'm going to take a quick gander at rephrasing your question and it's requirements. It sounds to me like you want to be able to load binary file objects, in this case pictures, using VBA, an OLE Object field in your table, and a Bound Object Frame.

Your best option is to stop trying to use a bound object frame because it has far too many limitations.

There are basically two recommended methods for what you're trying to do.

1) Store only a link to the image file and then use an image control (it can be bound to your picture field) to display the image.

2) Store the image in an OLE Object field using code to read the image in as binary data. When you need to display the image you'll need to write it out to a temp file and then you can set the Picture property on an Image Control to the full path and filename for the temporary image file. It will be up to you to manage the image file as a temp file. You could use Windows' temp directory or you can simply write out to the same file name every time you need to display an image.

Neither of these techniques are overly difficult. There's a really good article here to help you further understand what I'm talking about: http://www.jamiessoftware.tk/articles/handlingimages.html

Here's a function to read in binary data (in this case your picture file) and another function to write out binary data: http://www.ammara.com/access_image_faq/read_write_blob.html This works well for writing your picture out to a "temp" file. Then all you have to do is set the Picture property on your image control to be the file path and name of your temp file.

You can also read and write binary data using an ADO Stream object, together with an ADO RecordSet Object and ADO Connection Object. You'll have to set a reference in Access to Microsoft ActiveX Data Objects 2.8 Library.

Here's some code to add pictures to the database using ADO:

Private Function LoadPicIntoDatabase(sFilePathAndName As String) As Boolean
On Error GoTo ErrHandler

    'Test to see if the file exists. Exit if it does not.
    If Dir(sFilePathAndName) = "" Then Exit Function

    LoadPicIntoDatabase = True

    'Create a connection object
    Dim cn As ADODB.Connection
    Set cn = CurrentProject.Connection

    'Create our other variables
    Dim rs As ADODB.Recordset
    Dim mstream As ADODB.Stream
    Set rs = New ADODB.Recordset

    'Configure our recordset variable and open only 1 record (if one exists)
    With rs
        .LockType = adLockOptimistic
        .CursorLocation = adUseClient
        .CursorType = adOpenDynamic
        .Open "SELECT TOP 1 * FROM tblArticles", cn
    End With

    'Open our Binary Stream object and load our file into it
    Set mstream = New ADODB.Stream
    mstream.Open
    mstream.Type = adTypeBinary
    mstream.LoadFromFile sFilePathAndName

    'add a new record and read our binary file into the OLE Field
    rs.AddNew
    rs.Fields("olepicturefield") = mstream.Read
    rs.Update

    'Edit: Removed some cleanup code I had inadvertently left here.


Cleanup:
    On Error Resume Next
    rs.Close
    mstream.Close
    Set mstream = Nothing
    Set rs = Nothing
    Set cn = Nothing

    Exit Function

ErrHandler:
    MsgBox "Error: " & Err.Number & " " & Err.Description
    LoadPicIntoDatabase = False
    Resume Cleanup

End Function


Private Sub Command0_Click()
    If IsNull(Me.txtFilePathAndName) = False Then
        If Dir(Me.txtFilePathAndName) <> "" Then
            If LoadPicIntoDatabase(Me.txtFilePathAndName) = True Then
                MsgBox Me.txtFilePathAndName & " was successfully loaded into the database."
            End If
        End If
    End If
End Sub

Edit1:

As per your request, here's code to lookup/load a picture for a given article. For the sake of consistency, I've also changed my table and field names above to better reflect your project and to match the code below. I tested this code and it worked properly for me.

Private Sub Command1_Click()
    If IsNull(Me.txtArticleID) = False Then
        If DCount("articleid", "tblArticles", "articleid = " & Me.txtArticleID) = 1 Then
            Dim rs As DAO.Recordset, sSQL As String, sTempPicture As String
            sSQL = "SELECT * FROM tblArticles WHERE ArticleID = " & Me.txtArticleID
            Set rs = CurrentDb.OpenRecordset(sSQL)
            If Not (rs.EOF And rs.BOF) Then
                sTempPicture = "C:\MyTempPicture.jpg"
                Call BlobToFile(sTempPicture, rs("olepicturefield"))
                If Dir(sTempPicture) <> "" Then
                    Me.imagecontrol1.Picture = sTempPicture
                End If
            End If
            rs.Close
            Set rs = Nothing
        Else
            MsgBox "Article Not Found"
        End If
    Else
        MsgBox "Please enter an article id"
    End If
End Sub

Private Function BlobToFile(strFile As String, ByRef Field As Object) As Long
    On Error GoTo BlobToFileError

    Dim nFileNum As Integer
    Dim abytData() As Byte
    BlobToFile = 0
    nFileNum = FreeFile
    Open strFile For Binary Access Write As nFileNum
    abytData = Field
    Put #nFileNum, , abytData
    BlobToFile = LOF(nFileNum)

BlobToFileExit:
    If nFileNum > 0 Then Close nFileNum
    Exit Function

BlobToFileError:
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, _
           "Error writing file in BlobToFile"
    BlobToFile = 0
    Resume BlobToFileExit

End Function        
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文