[英]import multiple csv to excel vba
I want to Import multiples csv file to excel sheet but when the second csv file open the data of the first csv lost . 我想将多个csv文件导入到Excel工作表,但是当第二个csv文件打开时,第一个csv的数据丢失了。
Here is my code: 这是我的代码:
Sub Test_ImportAllFiles()
Dim vaArray As Variant
Dim i As Integer
Dim oFile As Object
Dim oFSO As Object
Dim oFolder As Object
Dim oFiles As Object
sPath = Application.ThisWorkbook.Path & "\cdr"
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files
If oFiles.Count = 0 Then Exit Sub
ReDim vaArray(1 To oFiles.Count)
i = 1
For Each oFile In oFiles
vaArray(i) = Application.ThisWorkbook.Path & "\cdr\" & oFile.Name
row_number = CStr(Cells(Rows.Count, 1).End(xlUp).Row)
With Sheets("Sheet2").QueryTables.Add("TEXT;" + vaArray(i), Destination:=Sheets("Sheet2").Range("$A$" + row_number))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 3
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Dim wb_connection As WorkbookConnection
For Each wb_connection In ActiveWorkbook.Connections
If InStr(vaArray(i), wb_connection.Name) > 0 Then
wb_connection.Delete
MsgBox "Antonis" & i
End If
Next wb_connection
i = i + 1
Next
End Sub
When you count the number of rows, you are referring to the active sheet, and that's possibly not the sheet where you want to write the data to. 计算行数时,是指活动工作表,而这可能不是要将数据写入其中的工作表。
Try something like 尝试类似
Dim x as long
With Sheets("Sheet2")
row_number = .Cells(.Rows.Count, 1).End(xlUp).Row)
if row_number > 1 then row_number = row_number + 1
end With
With Sheets("Sheet2").QueryTables.Add("TEXT;" + vaArray(i), _
Destination:=Sheets("Sheet2").Range("$A$" & row_number))
Update : Add one to row_number, else the ranges will overlap, and as a QueryTable may not overlap, Excel moves them. 更新 :将一个数字添加到row_number上,否则范围将重叠,并且由于QueryTable可能不重叠,Excel将移动它们。
And yes, you can use a number for the rowcount variable, you just have to change the string concatenation from +
to &
. 是的,您可以为rowcount变量使用数字,只需将字符串连接从
+
更改为&
。 The operator +
works for concatenation only if both sides are strings, while &
does an implicit conversion to string for all data types. 仅当双方都是字符串时,运算符
+
才可进行串联,而对于所有数据类型, &
运算符都将隐式转换为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.