【发布时间】:2017-06-17 23:42:22
【问题描述】:
我有一个包含 2000 个 *.csv 文件的文件夹。但并非所有这些都是重要的 4 我。其中只有 60 个是重要的,我在访问表中按名称列出了它们。没有标题 - 只有需要读入单表数据库的文件名。 它看起来像这样:
这些 *.mst 文件实际上是 *.csv 文件 - 它会以这种方式工作。 我需要一个 VBA 过程,它只将选定的文件(表中列出的这些文件)从此文件夹中导入到单个访问表中。 是的,所有这些文件都具有完全相同的结构,因此它们可以合并到这些访问表中,这就是这个 VBA 过程的目标。
我已经获得的代码只是从该文件夹中提取每个文件并将其导入到访问中的单个表中。 我需要将其更改为仅提取选定的文件。 目标表名是:“all_stocks”
Sub Importing_data_into_a_single_table()
Dim start As Double
Dim total_time As String
Dim my_path As String, my_ext As String, my_file As String
Dim FileNum As Integer
Dim DataLine As String
Dim pola() as String
Dim SQL1 As String, file_array() As String
start = Timer
my_path = "C:\Users\michal\SkyDrive\csv\bossa\mstcgl_mst\" 'Source folder.
my_ext = "*.mst" ' all files with .mst extension.
my_file = Dir(my_path & my_ext) ' take the first file from my_path.
DoCmd.SetWarnings False ' turn off warnings.
Do While my_file <> ""
FileNum = FreeFile()
Open my_path & my_file For Input As #FileNum
Line Input #FileNum, DataLine
' Reads a single line from an open sequential file and assigns it to a String variable.
While Not EOF(FileNum) ' EOF function returns a Boolean value True when the end of a file.
Line Input #FileNum, DataLine
pola = Split(DataLine, ",")
SQL1 = "INSERT INTO Tabela1 (Ticker, day, open, high, low, close, vol) VALUES('" & pola(0) & "', " & _
pola(1) & ", " & pola(2) & ", " & pola(3) & ", " & _
pola(4) & ", " & pola(5) & ", " & pola(6) & ")"
Debug.Print SQL1
DoCmd.RunSQL SQL1
Wend
Close
my_file = Dir()
Loop
DoCmd.SetWarnings True
total_time = Format((Timer - start) / 86400, "hh:mm:ss")
' total_time = Round(Timer - start, 3)
MsgBox "This code ran successfully in " & total_time & " minutes", vbInformation
End Sub
如果您可以优化此代码以更快地运行,请成为我的客人。 现在它使用“Line Input”方法导入数据,我听说有一些更好的方法可以做到这一点,但我自己不是程序员,所以我依赖于你的帮助我的朋友们。 感谢您提供的所有帮助和代码:-)
【问题讨论】: