我想将多个csv文件导入Excel工作表 但是当第二个csv文件打开时,第一个csv的数据丢失了。
这是我的代码:
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
答案 0 :(得分:0)
计算行数时,是指活动工作表,可能不是要向其写入数据的工作表。
尝试类似
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))
更新:在row_number中添加一个,否则范围将重叠,并且由于QueryTable可能不重叠,因此Excel将它们移动。
是的,可以为rowcount变量使用数字,只需要将字符串连接从+
更改为&
。仅当双方都是字符串时,运算符+
才可以进行串联,而对于所有数据类型,&
都将隐式转换为字符串。