我是 VBA 的新手,我正在尝试自动化一个将特定文件夹中的 4 个 .csv 文件导入 SQL 数据库的过程。我有一个代码,其中有 4 个命令按钮,在每个 4 个中,我选择文件,然后将它们导入 SQL。但是,我想知道是否有一种方法可以让我只有一个命令按钮,从该特定文件夹中选择所有 .csv 文件,然后将它们导入 SQL。假设文件夹名称为以下路径中的数据库:Y:\Data\Database
我有以下导入按钮代码,可将本地路径转换为 SQL 服务器路径以及所有其他类型的函数以将数据导入 SQL 服务器。(fName1...fName4 是用户当前选择的 4 个文件路径的 TextBox 值)
Private Sub ImportButton_Click()
Dim fName1 As String
Dim fName2 As String
Dim fName3 As String
Dim fName4 As String
Dim perc As Single
Dim index As Integer
Dim subStr As String
Dim sqlStr As String
sqlStr = "E:\Analytics\"
'Convert the local path to SQL server path
fName1 = TextBox1.Value
index = InStr(1, fName1, "\")
subStr = Left(fName1, index)
fName1 = Replace(fName1, subStr, sqlStr, , 1)
fName2 = TextBox2.Value
index = InStr(1, fName2, "\")
subStr = Left(fName2, index)
fName2 = Replace(fName2, subStr, sqlStr, , 1)
fName3 = TextBox3.Value
index = InStr(1, fName3, "\")
subStr = Left(fName3, index)
fName3 = Replace(fName3, subStr, sqlStr, , 1)
fName4 = TextBox4.Value
index = InStr(1, fName4, "\")
subStr = Left(fName4, index)
fName4 = Replace(fName4, subStr, sqlStr, , 1)
'Modify the text captions for test purpose
TextBox1.Value = fName1
TextBox2.Value = fName2
TextBox3.Value = fName3
TextBox4.Value = fName4
Dim cnPubs As ADODB.Connection
Dim cmd As ADODB.Command
' Create a connection object.
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to the Pubs database on server hcdcd-actstat01 .
strConn = strConn & "DATA SOURCE=hcdcd-actstat01;INITIAL CATALOG=Analytics;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cnPubs.Open strConn
Set cmd = New ADODB.Command
cmd.ActiveConnection = cnPubs
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "dbo.Proc_CapitalAllocation_Step1"
cmd.CommandTimeout = 1200 'Seconds
''cmd.Parameters.Append cmd.CreateParameter_(fName1, fName2, fName3, fName4)
Call cmd.Execute(Parameters:=Array(fName1, fName2, fName3, fName4), Options:=adCmdStoredProc)
End Sub
任何帮助,将不胜感激。太感谢了。