VBA利用ADO合併多個CSV

2021-09-25 12:57:28 字數 2428 閱讀 4691

sub 合併多個csv檔案為乙個檔案()

dim cnn as object, sql$, mypath$, myfile$, m&

set cnn = createobject("adodb.connection")

set rs = createobject("adodb.recordset")

mypath = thisworkbook.path & "\"

if dir(mypath & "total.csv") <> "" then kill mypath & "total.csv"

myfile = dir(mypath & "*.csv")

do while myfile <> ""

n = n + 1

if sql = "" then sql = "select eutrancelltdd,count(erbs) as num,sum(voice_erl) as voice_erl from [" & myfile & "] group by eutrancelltdd" else sql = sql & " union all select * from " & myfile

myfile = dir()

loop

cnn.open "provider=microsoft.ace.oledb.12.0;extended properties='text;fmt=delimited';data source=" & mypath

sql = "select eutrancelltdd,sum(num) as n ,sum(voice_erl) as voice_erl into [total.csv] from (" & sql & ")" & " group by eutrancelltdd"

cnn.execute sql

msgbox m & "個csv檔案已成功合併為total.csv!"

cnn.close

set cnn = nothing

end sub

sub 指定字段合併()

dim cnn as object, sql$, mypath$, myfile$, m&

set cnn = createobject("adodb.connection")

set rs = createobject("adodb.recordset")

mypath = thisworkbook.path & "\"

if dir(mypath & "total.csv") <> "" then kill mypath & "total.csv"

myfile = dir(mypath & "*.csv")

do while myfile <> ""

n = n + 1

'if sql1 = "" then sql1 = "select 開始時間,[imei tac],[手機型別],[ua],[手機廠家],[手機型號],起始5g小區,起始4g小區,結束4g小區, sip首拆reason頭域sip原因值,sip首拆reason頭域sip警告正文,第一s1錯誤碼 from [" & myfile & "] " else sql1 = sql1 & " union all select 開始時間,[imei tac],[手機型別],[ua],[手機廠家],[手機型號],起始5g小區,起始4g小區,結束4g小區, sip首拆reason頭域sip原因值,sip首拆reason頭域sip警告正文,第一s1錯誤碼 from " & myfile

if sql1 = "" then sql1 = worksheets("sql語句").cells(1, 18) & "from [" & myfile & "] " else sql1 = sql1 & " union all " & worksheets("sql語句").cells(1, 18) & " from " & myfile

myfile = dir()

loop

cnn.open "provider=microsoft.ace.oledb.12.0;extended properties='text;fmt=delimited';data source=" & mypath

'sql1 = "select 開始時間,[imei tac],[手機型別],[ua],[手機廠家],[手機型號],起始5g小區,起始4g小區,結束4g小區, sip首拆reason頭域sip原因值,sip首拆reason頭域sip警告正文,第一s1錯誤碼 into [total.csv] from (" & sql1 & ")"

sql1 = worksheets("sql語句").cells(1, 18) & " into [total.csv] from (" & sql1 & ")"

cnn.execute sql1

msgbox n & "個csv檔案已成功合併為total.csv!"

cnn.close

end sub

vba合併多個Excel文件

引用自 僅適用於每個sheet的第一行是資料頭,資料從第二行開始。sub 合併工作簿 dim fileopen dim x as integer remexcel 97 2003 工作簿 xls xls multiselect true,title 請選擇需要合併的工作簿 x 1 if typena...

VBA 合併多個工作簿

合併多個工作薄,並以工作薄的名字給sheet表命名 每個工作薄只有一張表 subtest dimstr asstring dim wb as workbook str dir c users administrator desktop 6.3 6.7 xls for i 1 to100 set wb...

pandas合併多個csv檔案

import pandas as pd importos 檔案路徑注意用 inputfilepath c users administrator aaa bbb outputfilepath c users administrator aaa df filename file 8 27 11 19....