从目录中提取文件名

  • 本文关键字:提取 文件名 excel vba
  • 更新时间 :
  • 英文 :


我是VBA新手。我写了一个代码来从文本文件导入数据,它的一部分是提示用户选择要打开的文件。我的问题是如何提取文件名并将其保存在单元格中或者甚至将其分配给变量,例如x。

Sub Macro1()
'
' Macro1 Macro
'
ChDir "C:Usersmajed502DocumentsVBA WORKVBA"

the_file_picked = Application.GetOpenFilename("Text Files (*.txt), *.txt")

Workbooks.OpenText Filename:= _
the_file_picked, Origin:=437, _
StartRow:=4, DataType:=xlFixedWidth, FieldInfo:=Array(Array(0, 1), Array(11 _
, 1), Array(23, 1), Array(28, 1), Array(43, 1), Array(53, 1)), TrailingMinusNumbers:= _
True
'Sheets("Nov2007").Select
ActiveSheet.Move Before:=Workbooks("monthly update.xlsm").Sheets(1)

Rows("1:2").Select
Selection.Delete Shift:=xlUp

Columns("A:A").Select
Selection.Insert Shift:=xlToRight
Range("A1").Select
ActiveCell.FormulaR1C1 = Left(ActiveSheet.Name, 7)
End Sub

我目前正在从表单名称中取出名称但我想从文件名

中取出名称

为了从整个路径中检索文件名,您可以使用以下宏:

Sub test()
Dim a As String
a = "C:Temp_Folderblabla.txt"
iSplit = InStrRev(a, "")
strName = Right(a, Len(a) - iSplit)
End Sub

=比;strName= "blabla.txt",即文件名。

作为一个在线用户,你可以在这里输入:

strName = Right(str_Path, Len(str_Path) - InStrRev(str_Path, ""))

…其中strPath为文件的全路径。

试试下面的子标题。

Sub LoopThroughFiles()
Dim StrFile, FolderPath As String
Dim StartCell As Range
Dim i As Long

With Application.FileDialog(msoFileDialogFolderPicker)
.Show
FolderPath = .SelectedItems(1)
End With
StrFile = Dir(FolderPath & "")  'Dir("c:testfolder*test*") --- Dir("C:UsersHARUNMusic*.xlsx")

Set StartCell = Application.InputBox(Prompt:="Select a cell to put file names. ", Type:=8)

i = StartCell.Row
Do While Len(StrFile) > 0
'Debug.Print StrFile
Cells(i, StartCell.Column) = StrFile
StrFile = Dir
i = i + 1
Loop
End Sub
  • 提示用户选择一个文件夹
  • 然后会提示选择一个单元格来存放文件名。
  • 根据需要修改代码

最新更新