使用VBA设置单元格值

时间:2016-08-26 11:36:20

标签: vba ms-access access-vba wia

我在Microsoft Access中使用VBA扫描并使用Wia保存图像。

应将保存图像的文件路径设置为当前单元格的值。

我无法弄清楚如何做到这一点,但在学习如何使用Wia之后这似乎是一件容易的事。

这是我当前扫描文档的代码。

Function scanImage() As String
    Dim imagePath As String
    Dim folder As String
    folder = "C:\Users\username\Pictures\scans\"
    Dim tempName, obj
    Set obj = CreateObject("Scripting.FileSystemObject")
    tempName = obj.GetTempName
    Dim filename
    filename = Now
    filename = Replace(filename, ".", "_")
    filename = Replace(filename, " ", "_")
    filename = Replace(filename, ":", "_")
    imagePath = folder & filename & ".jpg"

    Dim dev As Device
    Dim wiaDialog As New WIA.CommonDialog
    Dim wiaImage As WIA.ImageFile
    Set dev = wiaDialog.ShowSelectDevice
    Set wiaImage = wiaDialog.ShowAcquireImage
    wiaImage.SaveFile (imagePath)
    scanImage = imagePath

End Function

1 个答案:

答案 0 :(得分:1)

正如评论所说 - Access中没有单元格,绝对没有活动单元格。 您可以使用以下任一方法将记录添加到数据库,但是如何计划再次提取该信息?

在Excel中,您只需要单元格A1中的数据,但在数据库中,您通常会要求来自一个或多个字段的数据,其中同一记录上的另一个字段等于其他一些值(通过提供'其他值'直接或通过引用数据库中的其他表)。

因此,例如,在您的数据库中,您要求提供在特定日期扫描的所有文件的文件路径,或者使用某种描述字段来标识文件。
这将写成如下:
SELECT FilePath FROM Table2 WHERE DescriptionField = 'MyPhoto'

无论如何,将单个文本字符串(imagepath)放入表中的新记录的答案是:

Sub InsertValueToTable()

    Dim imagepath As String

    imagepath = "<file path>"

    'NB:  The table name is 'Table2', the field (column) within the table is called 'FilePath'.

    'One way to do it:
    'DoCmd.RunSQL "INSERT INTO Table2(FilePath) VALUES ('" & imagepath & "')"

    'Another way to do it:
    Dim rst As dao.Recordset
    Set rst = CurrentDb.OpenRecordset("Table2")
    With rst
        .AddNew
        rst!FilePath = imagepath
        .Update
        .Close
    End With

    Set rst = Nothing

End Sub  

注意 - 如果您在数据库中使用Text字段,则限制为255个字符。