我在Microsoft Access中使用vba代码一次导入多个csv文件,遗憾的是,并非所有csv文件都具有相同的格式;有些文件只有[SKU-1],但有些文件有第二个字段[SKU-2]。
我的代码如下所示,对于同时包含sku-1和sku-2作为csv文件中的字段的文件,但是,如果文件只有[SKU-1],导入将失败,并且#34;参数太少。预计1。"
有没有办法使用某种case语句来删除SKU-2的NULL值,如果该字段本身不存在而无法从中拉出?
CurrentDb.Execute "INSERT INTO MumbyCSV (OrderID, Email, FirstName, LastName, Company, Phone, SecondaryPhone," & _
"Fax, ApproveStatus, OrderDate, [SKU-1], [SKU-2], Total, ShiptoName, ShipToAddress1, ShipToAddress2," & _
"ShipToCity, ShipToState, ShipToZip, ShipToCountry, ShippingMethod, Comments)" & _
"SELECT OrderID, Email, FirstName, LastName, Company, Phone, SecondaryPhone," & _
"Fax, ApproveStatus, OrderDate, [SKU-1], [SKU-2], Total, ShiptoName, ShipToAddress1, ShipToAddress2," & _
"ShipToCity, ShipToState, ShipToZip, ShipToCountry, ShippingMethod, Comments " & _
"FROM [Text;FMT=Delimited;HDR=YES;DATABASE=C:\ImportPath].[test.csv]"
答案 0 :(得分:0)
首先检查文件中的字段数:
dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
dim file : Set file = fso.OpenTextFile("C:\ImportPath\test.csv")
firstLine = file.ReadLine ' read first line
fieldArray = Split(firstLine, "whateverfielddelimiteryouhave")
numFields = UBound(fieldArray) + 1 'index on arrays from zero
这将告诉你有多少个字段。如果您使用和不使用[SKU-2]
定义了SQL,则可以使用简单的IF
来选择要执行的SQL:
If numFields = 22 Then
sql = "INSERT INTO MumbyCSV (OrderID, Email, FirstName, LastName, Company, Phone, SecondaryPhone," & _
"Fax, ApproveStatus, OrderDate, [SKU-1], [SKU-2], Total, ShiptoName, ShipToAddress1, ShipToAddress2," & _
"ShipToCity, ShipToState, ShipToZip, ShipToCountry, ShippingMethod, Comments)" & _
"SELECT OrderID, Email, FirstName, LastName, Company, Phone, SecondaryPhone," & _
"Fax, ApproveStatus, OrderDate, [SKU-1], [SKU-2], Total, ShiptoName, ShipToAddress1, ShipToAddress2," & _
"ShipToCity, ShipToState, ShipToZip, ShipToCountry, ShippingMethod, Comments " & _
"FROM [Text;FMT=Delimited;HDR=YES;DATABASE=C:\ImportPath].[test.csv]"
Else
sql = "INSERT INTO MumbyCSV (OrderID, Email, FirstName, LastName, Company, Phone, SecondaryPhone," & _
"Fax, ApproveStatus, OrderDate, [SKU-1], Total, ShiptoName, ShipToAddress1, ShipToAddress2," & _
"ShipToCity, ShipToState, ShipToZip, ShipToCountry, ShippingMethod, Comments)" & _
"SELECT OrderID, Email, FirstName, LastName, Company, Phone, SecondaryPhone," & _
"Fax, ApproveStatus, OrderDate, [SKU-1], Total, ShiptoName, ShipToAddress1, ShipToAddress2," & _
"ShipToCity, ShipToState, ShipToZip, ShipToCountry, ShippingMethod, Comments " & _
"FROM [Text;FMT=Delimited;HDR=YES;DATABASE=C:\ImportPath].[test.csv]"
End If
CurrentDB.Execute sql
第二个选项是读取要导入到数组中的值,并且值为空字符串,将其替换为NULL,以便在INSERT步骤中不设置该字段。但是,如果您必须按照您的代码直接从文件导入,我认为您不能这样做。
答案 1 :(得分:0)
考虑使用不需要任何列顺序的TransferText并忽略丢失的列,只要导入的当前文件在表中的某处保留列:
DoCmd.TransferText acImportDelim, , "MumbyCSV", "C:\ImportPath\test.csv", True