簡體   English   中英

excel 在訪問中使用 vba 導入文本文件

[英]excel import text file using vba in access

我有一個文本文件需要從訪問權限導入 excel。 我已經構建了 vba 來生成文本文件,將其放在一個文件夾中,我有代碼來獲取我的 excel 模板並復制它。

但現在要將文本文件導入我的工作簿中的選項卡,我遇到了麻煩。 我可以在 excel 中手動導入文本文件,但如果我可以在訪問中做同樣的事情,我的所有流程都會完全自動化。

我有想法並構建了我能做的,但它讀取我正在繪制空白的文本文件的那部分。

sub updatereport_Click()

Set rsquery1 =  ???

Set excelapp = CreateObject("Excel.application", "")
excelapp.Visible = True

Set XL = CreateObject("Excel.Application")

Set targetworkbook = excelapp.workbooks.Open(drive & Inputlocation & Inputcurrentsunday & "\" & "AgentSchedulesDOW-Verint_WkOf_" & Inputcurrentsunday & ".xlsx")

targetworkbook.worksheets("Data").Range("A2:BO45000").clearcontents
targetworkbook.worksheets("Data").Range("A2").copyfromrecordset rsquery1

targetworkbook.Save
targetworkbook.Close

XL.workbooks.Close
XL.Quit

excelapp.workbooks.Close

End Sub

這可能有幫助嗎? http://www.freevbcode.com/ShowCode.asp?ID=2180

組合代碼如下所示:

Sub updatereport_Click()

Dim connCSV As New ADODB.Connection
Dim rsquery1 As New ADODB.Recordset
Dim adcomm As New ADODB.Command
Dim path As String

path = "C:\Testdir\"  'Here Test dir is the Directory where
' the text file is located. don't write the file name here.

'This is connection for a text file without Header

 'connCSV.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
 & path & ";Extended Properties='text;HDR=NO;FMT=Delimited'"


'This is connection for a text file with Header (i.e., columns
 
connCSV.Open "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
& path & ";Extensions=asc,csv,tab,txt;HDR=NO;Persist Security Info=False"
    
    
   rsquery1.Open "Select * From test.txt", _
       connCSV, adOpenStatic, adLockReadOnly, adCmdText


Set excelapp = CreateObject("Excel.application", "")
excelapp.Visible = True

Set XL = CreateObject("Excel.Application")

Set targetworkbook = excelapp.Workbooks.Open(drive & Inputlocation & Inputcurrentsunday & "\" & "AgentSchedulesDOW-Verint_WkOf_" & Inputcurrentsunday & ".xlsx")

targetworkbook.Worksheets("Data").Range("A2:BO45000").ClearContents
targetworkbook.Worksheets("Data").Range("A2").CopyFromRecordset rsquery1

targetworkbook.Save
targetworkbook.Close

XL.Workbooks.Close
XL.Quit

您可能需要更改以下內容,但絕對需要:

  1. 將文本文件位置的路徑放在第 8 行
  2. 在第 23 行更新測試文件的名稱
  3. 取決於您的文本文件是否有 header 可能需要注釋/取消注釋相應的 connCSV.open 代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM