我想选择多个文件,并将其名称显示在一个主工作簿的列中。我的代码在这里运行,但文件名并没有像我想要的那样出现,而且作为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
提前感谢您的帮助!
答案 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