这里我有一个加载CSV文件的代码。 它看起来像这样:
Sub Main()
Dim CDLG As Object
Set CDLG = CreateObject("MSComDlg.CommonDialog")
With CDLG
.DialogTitle = "Choose file"
.Filter = "CSV Documents|*.csv"
.ShowOpen
m_strFileURI = .Filename
m_strFileName = .FileTitle
Dim cesta As String
cesta = Left(m_strFileURI, InStrRev(m_strFileURI, "\"))
End With
Set CDLG = Nothing
Dim FSO As New FileSystemObject
'array of values in each line
Dim LineValues() As String
'each new line read in from the text stream
Dim ReadLine As String
Dim ts As TextStream
'open file
Set ts = FSO.OpenTextFile(m_strFileURI)
'keep going till no more lines
Do Until ts.AtEndOfStream
'read first line
ReadLine = ts.ReadLine
LineValues = Split(ReadLine, ",")
Debug.Print LineValues(3)
**'--> Need finaly generate filename as: Totalqty - lenght - width**
Loop
End Sub
我用它解析它:
{{1}}
但我如何从 - LineValues(3)获得TOTAL QTY 所以我可以用它来创建一个包含Totalqty的文件名 - lenght - width ??
谢谢
答案 0 :(得分:1)
添加一个名为TotaLineValues的新变量,并使用每个LineValues(3)递增它
在Sub的顶部添加此
Dim TotalLineValues As Long
TotalLineValues = 0
在Loop
添加此内容之前:
TotalLineValues = TotalLineValues + LineValues(3)
Debug.Print TotalLineValues
每次都会看到总增量值
编辑:要查询文件并一次性汇总QTY,在循环之前,尝试将其作为SQL对象查询:
Public Sub GetDataFromCSV()
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
strPathtoTextFile = "C:\temp\"
strFile = "tesFile.csv"
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPathtoTextFile & ";Extended Properties='text;HDR=YES;FMT=Delimited'"
objRecordSet.Open "Select sum(QTY) as Quantity from " & strFile, objConnection, adOpenStatic, adLockOptimistic, adCmdText
If Not objRecordSet.EOF Then
Debug.Print objRecordSet.Fields.Item("Quantity") ' This will tell you the total quantity in the file is 7
End If
End Sub