|
楼主 |
发表于 2024-1-13 12:27
|
显示全部楼层
搞定了,目前看来只有这一种方法,就是schema.ini的方式
Sub 带点五()
startTime = Timer
file_path_name = Application.GetOpenFilename()
file_path = Left(file_path_name, Len(file_path_name) - Len(Dir(file_path_name)) - 1) & "\"
sheet_name = ActiveSheet.Name
With CreateObject("Scripting.FileSystemObject") '获取列名
cols = Split(.OpenTextFile(file_path_name, 1).ReadLine, ",")
End With
n = FreeFile 'schema.ini文件按照列名全部设置文本格式
i = 0
Open file_path & "schema.ini" For Output As #n
Print #n, "[" & Dir(file_path_name) & "]" & vbCrLf & "COLNAMEHEADER = TRUE" & vbCrLf & "Format = CSVDelimited"
For Each col In cols
i = i + 1
Print #n, "Col" & i & "=" & col & " Char" '加上分号就不用添加换行
Next
Print #n,
Close #n
Set conn = CreateObject("ADODB.Connection") '初始化连接对象 'Set obj_rs = CreateObject("ADODB.Recordset")
conn.Open "Provider=Microsoft.ACE.OLEDB.16.0;Extended Properties=text;Data Source=" & file_path 'conn = "Driver={Microsoft Text Driver (*.txt; *.csv)};Extensions=csv;HDR=Yes;Dbq=" & file_path '仅32位可用Microsoft Access Text Driver
For x = 3 To Sheets(sheet_name).Cells(Sheets(sheet_name).Rows.Count, 21).End(xlUp).Row
line_start = Sheets(sheet_name).Cells(x, 21)
line_end = Sheets(sheet_name).Cells(x, 22)
point_start = Sheets(sheet_name).Cells(x, 23)
point_end = Sheets(sheet_name).Cells(x, 24)
If x = 3 Then
sqlstr = "SELECT * FROM [" & Dir(file_path_name) & "] WHERE Val(Left([点号],6)) >= " & line_start & " and Val(Left([点号],6)) <= " & line_end
'str_sql = "SELECT * FROM [" & Dir(file_path_name) & "] WHERE Val(Left([点号],6)) >= " & line_start & " and Val(Left([点号],6)) <= " & line_end
'str_sql = "SELECT * FROM [" & Dir(file_path_name) & "] WHERE Left([点号], 4) >= '" & line_start & "' AND Left([点号], 4) <= '" & line_end & "' AND Right([点号],4) >= '5600.5' AND Right([点号],4) <= '5580.5';"
Else
sqlstr = sqlstr & " UNION ALL SELECT * FROM [" & Dir(file_path_name) & "] WHERE left([点号]) >= " & line_start & " and left([点号]) <= " & point_end
End If
Next x
out_path_name = file_path & CreateObject("Scripting.FileSystemObject").GetBaseName(file_path_name) & "-" & Format(Now(), "yyyy-mm-dd_hhmmss") & ".csv"
Set rs = conn.Execute(sqlstr)
Dim arrData() As Variant
arrData = rs.GetRows()
Set fs = CreateObject("Scripting.FileSystemObject")
Dim stream As Object
Set stream = fs.CreateTextFile(out_path_name, True)
' 导出表头
For i = 0 To UBound(arrData, 1)
stream.Write rs.Fields(i).Name
If i < UBound(arrData, 1) Then
stream.Write ","
End If
Next
'关闭连接对象和记录集
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
Kill file_path & "\schema.ini"
stream.Write vbNewLine
' 导出数据
For i = 0 To UBound(arrData, 2)
For j = 0 To UBound(arrData, 1)
stream.Write IIf(IsNull(arrData(j, i)), "", arrData(j, i))
If j < UBound(arrData, 1) Then
stream.Write ","
End If
Next
stream.Write vbNewLine
Next
' 关闭文件流
stream.Close
MsgBox "程序运行时间:" & Timer - startTime & " 秒"
End Sub |
|