2013-01-08 26 views
0

背景信息: 我對VBA或Access並不很瞭解,但我有一個創建文件的VBA腳本(KML是特定的,但這對我的問題沒有太大影響)在用戶計算機上,並使用鏈接到數據庫中的記錄的變量寫入。因此:如何將MS Access數據庫中附件的內容複製到VBA變量中?

Dim MyDB As Database 
Dim MyRS As Recordset 
Dim QryOrTblDef As String 
Dim TestFile As Integer 

    QryOrTblDef = "Table1" 
    Set MyDB = CurrentDb 
    Set MyRS = MyDB.OpenRecordset(QryOrTblDef) 
    TestFile = FreeFile 

    Open "C:\Testing.txt" 
    Print #TestFile, "Generic Stuff" 
    Print #TestFile, MyRS.Fields(0) 

我的情況: 我有一個非常大的字符串(與多邊形頂點座標的大名單文本文檔),我要添加到一個變量被打印到另一個文件(一個KML文件,在上面的例子中提到)。我希望將包含座標的文本文件作爲附件數據類型添加到Access數據庫,並將其內容複製到要用於上述腳本中的變量中。

我的問題: 有沒有一種方法,我可以訪問並從連接的文本文件(附加爲MS Access數據庫的一個領域內的附件數據類型)中的數據複製到一個變量,這樣我可以使用它在一個VBA腳本?

我發現: 我有麻煩finidng有關此主題的信息,我想主要是因爲我沒有什麼關鍵字進行搜索的知識,但我能找到一個論壇上某人的代碼,「ozgrid」,這似乎接近我想要做的事情。雖然它只是從磁盤上的文本文件提取,而不是附加到數據庫上的文本文件。從上述論壇

代碼創建了一個函數在一個文本文件來訪問數據:

Sub Test() 

    Dim strText As String 

    strText = GetFileContent("C:\temp\x.txt") 
    MsgBox strText 

End Sub 

Function GetFileContent(Name As String) As String 
    Dim intUnit As Integer 

    On Error Goto ErrGetFileContent 
    intUnit = FreeFile 
    Open Name For Input As intUnit 
    GetFileContent = Input(LOF(intUnit), intUnit) 
ErrGetFileContent: 
    Close intUnit 
    Exit Function 
End Function 

這裏任何幫助表示讚賞。謝謝。

+0

你嘗試使用FSO(文件系統對象)。 http://stackoverflow.com/questions/9442215/reading-and-writing-a-csv-file-using-filesystemobject其他示例[4guysfromrolla](http://www.4guysfromrolla.com/webtech/faq/FileSystemObject/faq2 .shtml) – Hiten004

+0

感謝提示,正如我所說的,我在搜索關鍵字方面遇到了困難。文件系統對象看起來像它可以用於我的目的。很有幫助。 – Chaz

回答

1

我有點困惑,爲什麼一個備忘錄數據類型不適合如果你是存儲純文本,甚至有組織的文本表。這就是說,一種方法是輸出到磁盤並讀入字符串。

''Ref: Windows Script Host Object Model 
Dim fs As New FileSystemObject 
Dim ts As TextStream 
Dim rs As DAO.Recordset, rsA As DAO.Recordset 
Dim sFilePath As String 
Dim sFileText As String 

    sFilePath = "z:\docs\" 

    Set rs = CurrentDb.OpenRecordset("maintable") 
    Set rsA = rs.Fields("aAttachment").Value 

    ''File exists 
    If Not fs.FileExists(sFilePath & rsA.Fields("FileName").Value) Then 
     ''It will save with the existing FileName, but you can assign a new name 
     rsA.Fields("FileData").SaveToFile sFilePath 
    End If 

    Set ts = fs.OpenTextFile(sFilePath _ 
      & rsA.Fields("FileName").Value, ForReading) 

    sFileText = ts.ReadAll 

參見:http://msdn.microsoft.com/en-us/library/office/ff835669.aspx

+0

非常感謝Remou,這對我的目的非常有效。我也非常感謝代碼。我考慮過一個備忘錄,但我的理解是,備忘錄有60個字符的字符數限制,而我的最大字符串是大約340萬字符(大,多邊形的x,y和z頂點)。再次感謝。 – Chaz

+0

Remou,你有什麼想法如何做同樣的事情,但與嵌入的OLE對象,而不是附件? – Chaz

+0

@Chaz嵌入式OLE對象可能因包裝器而變得很痛苦。有沒有測試過的ac#解決方案(http://jvdveen.blogspot.in/2009/02/ole-and-accessing-files-embedded-in.html)以及Lebans的解決方案,如果您使用的是32位(http://www.lebans.com/oletodisk.htm)在MSDN上也有BLOB代碼(http://support.microsoft.com/kb/103257)。在某些情況下,ADODB流將起作用。 – Fionnuala

相關問題