将多个工作簿名称分配给VBA中的第一列

时间:2018-06-13 16:59:49

标签: excel vba

我想选择多个文件,并将其名称显示在一个主工作簿的列中。我的代码在这里运行,但文件名并没有像我想要的那样出现,而且作为VBA newb,我不知道为什么。这是我的代码:

Option Explicit

Sub FileNameExtraction()

Dim filenames As Variant
Dim wb As Workbook
Dim i As Long
Dim wbName As String
Dim rngdest As Range

Set rngdest = ThisWorkbook.ActiveSheet.Range("A1") '<< results start storing in this cell
filenames = Application.GetOpenFilename( _
FileFilter:="Excel Filter(*xlsx), *.xlsx", MultiSelect:=True)
If TypeName(filenames) = "Boolean" Then Exit Sub 'if nothing is selected, routine ends

For i = 1 To UBound(filenames) 'i counts the files selected

    Set wb = Workbooks.Open(filenames(i))
    wbName = wb.Name
    wbName = rngdest.Value
    Set rngdest = rngdest.Offset(1, 0)

    wb.Close False 'closes workbook without saving changes

Next i

End Sub

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您正在覆盖wbName的值而不将其放入工作表中。您需要将wbName = rngdest.Value更改为rngdest.Value = wbName

Sub FileNameExtraction()

Dim filenames As Variant
Dim wb As Workbook
Dim i As Long
Dim wbName As String
Dim rngdest As Range

Set rngdest = ThisWorkbook.ActiveSheet.Range("A1") '<< results start storing in this cell
filenames = Application.GetOpenFilename( _
FileFilter:="Excel Filter(*xlsx), *.xlsx", MultiSelect:=True)
If TypeName(filenames) = "Boolean" Then Exit Sub 'if nothing is selected, routine ends

For i = 1 To UBound(filenames) 'i counts the files selected

    Set wb = Workbooks.Open(filenames(i))
    wbName = wb.Name
    rngdest.Value = wbName '<== change here
    Set rngdest = rngdest.Offset(1, 0)

    wb.Close False 'closes workbook without saving changes

Next i

End Sub