0

以下代码允许我浏览多个不同的 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
4

1 回答 1

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)
于 2012-10-16T12:42:00.843 回答