gpt4 book ai didi

vba - 如何选择文件夹中的所有 .csv 文件,然后通过 VBA 编码将它们导入

转载 作者:行者123 更新时间:2023-12-04 22:09:27 25 4
gpt4 key购买 nike

我是 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

任何帮助,将不胜感激。
太感谢了。

最佳答案

这将帮助您遍历文件夹中的 .csv 文件。

Option Explicit

Sub LoopThroughFiles()

Dim strFile As String, strPath As String

strPath = "E:\Analytics\"
strFile = Dir(strPath & "*.csv")

While strFile <> ""

'-> code upload the file to SQL Database

strFile = Dir

Wend


End Sub

如果你需要更多的细化,比如你只想要某些 .csv文件夹中的文件,在 While strFile <> "" 后面添加语句清除您不想要的任何文件。就像是:
If InStr(1, strFile, "myName") > 0 Then
'-> code to upload the file to SQL database
End If

关于vba - 如何选择文件夹中的所有 .csv 文件,然后通过 VBA 编码将它们导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12182959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com