下面的代码允许我浏览多个不同的excel文件并将它们粘贴在彼此相同的单个工作表中.excel文件具有相同的列名但其中包含不同的数据并且工作正常,我的问题是我需要当它粘贴文件时,它还必须创建额外的列,并在该列中为每个粘贴的文件写入该文件的名称。
Sub Button5_Click()
Dim fileStr As Variant
Dim wbk1 As Workbook, wbk2 As Workbook
Dim ws1 As Worksheet
fileStr = Application.GetOpenFilename(FileFilter:="microsoft excel files (*.xlsx), *.xlsx", Title:="Get File", MultiSelect:=True)
Set wbk1 = ActiveWorkbook
Set ws1 = wbk1.Sheets("Sheet3")
'handling first file seperately
MsgBox fileStr(1), , GetFileName(CStr(fileStr(1)))
Set wbk2 = Workbooks.Open(fileStr(1))
wbk2.Sheets(1).UsedRange.Copy ws1.Cells(ws1.Range("A" & Rows.Count).End(xlUp).Row + 2, 1)
wbk2.Close
For i = 2 To UBound(fileStr)
MsgBox fileStr(i), , GetFileName(CStr(fileStr(i)))
Set wbk2 = Workbooks.Open(fileStr(i))
'using offset to skip the header - not the best solution, but a quick one
wbk2.Sheets(1).UsedRange.Offset(1, 0).Copy ws1.Cells(ws1.Range("A" & Rows.Count).End(xlUp).Row + 2, 1)
wbk2.Close
Next i
End Sub
答案 0 :(得分:1)
使用Insert
对象的Range
方法插入列:
'***** Inserts new column to the left of column C
Range("C:C").Insert
在单元格中输入文字:
'***** Entering text in A1
ws1.Cells(1, 1).Value = fileStr(i)