如何插入文件名

时间:2012-10-17 07:28:56

标签: vba excel-vba excel

下面的代码允许我浏览多个不同的excel文件并将它们粘贴在彼此相同的单个工作表中.excel文件具有相同的列名但其中包含不同的数据并且工作正常,我的问题是我需要当它粘贴文件时,它必须为它粘贴的每个文件写入该文件的名称。我的excel文件的名称称为 Familycar ,其他excel的文件名称为智能车

示例

eg1 CarName,Fuel,Color

BMW,汽油,红色

福特,柴油,绿

马自达,汽油,灰色

eg2 CarName,Fuel,Color

奥斯汀,汽油,蓝

VW,柴油,白

奥迪,汽油,黑色

结果

CarName,燃料,颜色,文件名

BMW,汽油,红色,的FamilyCar

福特,柴油,绿,的FamilyCar

马自达,汽油,灰色,的FamilyCar

奥斯汀,汽油,蓝,smatrtcar

VW,柴油,白色,智能车

奥迪,汽油,黑色,智能车

   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))

 wbk2.Sheets(1).UsedRange.Offset(1, 0).Copy ws1.Cells(ws1.Range("A" & Rows.Count).End(xlUp).Row + 2, 1)


 wbk2.Close
 Next i 

2 个答案:

答案 0 :(得分:3)

这是您的代码重构以包含此要求

Sub Button5_Click()
    Dim fileStr As Variant
    Dim wbk1 As Workbook, wbk2 As Workbook
    Dim ws1 As Worksheet
    Dim rngSource As Range
    Dim rngDest As Range
    Dim rwOffset As Long
    Dim sFileName As String

    Dim i As Long

    fileStr = Application.GetOpenFilename(FileFilter:="microsoft excel files (*.xlsx), *.xlsx", Title:="Get File", MultiSelect:=True)
    Set wbk1 = ActiveWorkbook
    Set ws1 = wbk1.Sheets("Sheet3")

    For i = 1 To UBound(fileStr)
        MsgBox fileStr(i), , GetFileName(CStr(fileStr(i)))

        ' Used to change copy range for first file, without repeating code
        rwOffset = IIf(i = 1, 0, 1)
        Set wbk2 = Workbooks.Open(fileStr(i))

        ' File Name without extension
        sFileName = Left$(wbk2.Name, InStrRev(fileStr(i), ".") - 1)  

        Set rngSource = wbk2.Sheets(1).UsedRange.Offset(rwOffset, 0)
        Set rngDest = ws1.Cells(ws1.Range("A" & ws1.Rows.Count).End(xlUp).Row + 2, 1)

        rngSource.Copy rngDest

        ' Add filename next to pasted data
        rngDest.Offset(0, rngSource.Columns.Count).Resize(rngSource.Rows.Count, 1) = sFileName
        wbk2.Close
    Next i

End Sub

答案 1 :(得分:1)

添加到您的代码

' ws1 is the result/output worksheet
' wbk2 is the input workbook I assume
Dim fromRow As Long
Dim toRow As Long
Dim colNum As Long 'please defind the column Number to output the workbook's name
' In your example, it would be 4
colNum = 4
fromRow = ws1.Cells(ws.Rows.Count, 1).End(xlUp).Row + 1
wbk2.Sheets(1).UsedRange.Offset(1, 0).Copy ws1.Cells(ws1.Range("A" & Rows.Count).End(xlUp).Row + 2, 1)
toRow = ws1.Cells(ws.Rows.Count, 1).End(xlUp).Row
ws1.Range(ws1.Cells(fromRow, colNum), ws1.Cells(toRow, colNum)).Value = wbk2.Name