I need to get file name without extension name by VBA. I know ActiveWorkbook.Name
property , but if user haves Windows property Hide extensions for known file types
turn off, the result of my code will be [Name.Extension]. How can I return only name of Workbook independent of windows property?
I try even ActiveWorkbook.Application.Caption
but I can’t customize this property.
asked Jan 13, 2015 at 14:02
0
The answers given here already may work in limited situations, but are certainly not the best way to go about it. Don’t reinvent the wheel. The File System Object in the Microsoft Scripting Runtime library already has a method to do exactly this. It’s called GetBaseName. It handles periods in the file name as is.
Public Sub Test()
Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetBaseName(ActiveWorkbook.Name)
End Sub
Public Sub Test2()
Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetBaseName("MyFile.something.txt")
End Sub
Instructions for adding a reference to the Scripting Library
answered Jan 13, 2015 at 14:51
RubberDuckRubberDuck
11.7k4 gold badges50 silver badges95 bronze badges
9
Simple but works well for me
FileName = ActiveWorkbook.Name
If InStr(FileName, ".") > 0 Then
FileName = Left(FileName, InStr(FileName, ".") - 1)
End If
answered Apr 19, 2017 at 7:39
IfcaIfca
1711 silver badge2 bronze badges
3
Using the Split function seems more elegant than InStr and Left, in my opinion.
Private Sub CommandButton2_Click()
Dim ThisFileName As String
Dim BaseFileName As String
Dim FileNameArray() As String
ThisFileName = ThisWorkbook.Name
FileNameArray = Split(ThisFileName, ".")
BaseFileName = FileNameArray(0)
MsgBox "Base file name is " & BaseFileName
End Sub
answered Jan 25, 2019 at 12:07
1
This gets the file type as from the last character (so avoids the problem with dots in file names)
Function getFileType(fn As String) As String
''get last instance of "." (full stop) in a filename then returns the part of the filename starting at that dot to the end
Dim strIndex As Integer
Dim x As Integer
Dim myChar As String
strIndex = Len(fn)
For x = 1 To Len(fn)
myChar = Mid(fn, strIndex, 1)
If myChar = "." Then
Exit For
End If
strIndex = strIndex - 1
Next x
getFileType = UCase(Mid(fn, strIndex, Len(fn) - x + 1))
End Function
answered Feb 20, 2019 at 16:05
You could always use Replace()
since you’re performing this on the workbook’s Name, which will almost certainly end with .xlsm
by virtue of using VBA.
Using ActiveWorkbook per your example:
Replace(Application.ActiveWorkbook.Name, ".xlsm", "")
Using ThisWorkbook:
Replace(Application.ThisWorkbook.Name, ".xlsm", "")
answered Nov 29, 2020 at 3:29
David MetcalfeDavid Metcalfe
2,1471 gold badge27 silver badges43 bronze badges
0
This thread has been very helpful to me lately. Just to extend on the answer by @RubberDuck, the File System Object in the Microsoft Scripting Runtime library is already there to achieve this. Also if you define it as an Object as below, it will save you the hassle of having to enable ‘Microsoft Scripting Runtime’ in VBA Tools > References:
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Debug.Print fso.GetBaseName(ActiveWorkbook.Name)
In this way it will return name of the ActiveWorkbook without extension.
There is another way by using INSTRREV function as below:
Dim fname As String
fname = Left(ActiveWorkbook.Name, InStrRev(ActiveWorkbook.Name, ".") - 1)
MsgBox fname
Both will return the same result. Also in both of the methods above, they will retain any full-stops in the file name and only get rid of the last full-stop and the file extension.
answered Jun 29, 2022 at 18:02
To be verbose it the removal of extension is demonstrated for
workbooks.. which now have a variety of extensions .
. a new unsaved Book1 has no ext
. works the same for files
Function WorkbookIsOpen(FWNa$, Optional AnyExt As Boolean = False) As Boolean
Dim wWB As Workbook, WBNa$, PD%
FWNa = Trim(FWNa)
If FWNa <> "" Then
For Each wWB In Workbooks
WBNa = wWB.Name
If AnyExt Then
PD = InStr(WBNa, ".")
If PD > 0 Then WBNa = Left(WBNa, PD - 1)
PD = InStr(FWNa, ".")
If PD > 0 Then FWNa = Left(FWNa, PD - 1)
'
' the alternative of using split.. see commented out below
' looks neater but takes a bit longer then the pair of instr and left
' VBA does about 800,000 of these small splits/sec
' and about 20,000,000 Instr Lefts per sec
' of course if not checking for other extensions they do not matter
' and to any reasonable program
' THIS DISCUSSIONOF TIME TAKEN DOES NOT MATTER
' IN doing about doing 2000 of this routine per sec
' WBNa = Split(WBNa, ".")(0)
'FWNa = Split(FWNa, ".")(0)
End If
If WBNa = FWNa Then
WorkbookIsOpen = True
Exit Function
End If
Next wWB
End If
End Function
answered Jan 29, 2017 at 21:44
Harry SHarry S
4616 silver badges5 bronze badges
I use a macro from my personal.xlsb and run it on both xlsm and xlsx files so a variation on David Metcalfe’s answer that I use is
Dim Wrkbook As String
Wrkbook = Replace(Application.ActiveWorkbook.Name, «.xlsx», «.pdf»)
Wrkbook = Replace(Application.ActiveWorkbook.Name, «.xlsm», «.pdf»)
answered Apr 6, 2021 at 14:04
VulkaVulka
134 bronze badges
Here is a solution if you do not want to use FSO.
There were some similar answers before, but here some checks are done to handle multiple dots in name and name without extension.
Function getFileNameWithoutExtension(FullFileName As String)
Dim a() As String
Dim ext_len As Integer, name_len As Integer
If InStr(FullFileName, ".") = 0 Then
getFileNameWithoutExtension = FullFileName
Exit Function
End If
a = Split(ActiveWorkbook.Name, ".")
ext_len = Len(a(UBound(a))) 'extension length (last element of array)
name_len = Len(FullFileName) - ext_len - 1 'length of name without extension and a dot before it
getFileNameWithoutExtension = Left(FullFileName, name_len)
End Function
Sub test1() 'testing the function
MsgBox (getFileNameWithoutExtension("test.xls.xlsx")) ' -> test.xls
MsgBox (getFileNameWithoutExtension("test")) ' -> test
MsgBox (getFileNameWithoutExtension("test.xlsx")) ' -> test
End Sub
answered May 2, 2022 at 16:37
LeoLeo
4203 silver badges18 bronze badges
strTestString = Left(ThisWorkbook.Name, (InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1))
full credit: http://mariaevert.dk/vba/?p=162
answered Jan 13, 2015 at 14:20
bp_bp_
4024 silver badges14 bronze badges
9
albert123 Пользователь Сообщений: 16 |
Доброго дня. Раньше встречались такие решения, тогда еще не было надобности, а сейчас хотел сделать но не мог найти пример. И так. Имеется файл по адресу D:Рабочий стол201912_ДЕКАБРЬфайл1.xlsb
Эх если бы нашел ответ на свое решение то вас бы не потревожил. Изменено: albert123 — 16.12.2019 20:06:19 |
Alemox Пользователь Сообщений: 2183 |
#2 16.12.2019 20:16:39 Имя файла без расширения:
Мастерство программиста не в том, чтобы писать программы, работающие без ошибок. |
||
albert123 Пользователь Сообщений: 16 |
Alemox,а обязательно надо будет писать адреса? просто там файлов в среднем 50, каждому прописывать, замучаюсь |
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
#4 16.12.2019 20:25:34 А так?
А так ? |
||
БМВ Модератор Сообщений: 21378 Excel 2013, 2016 |
#5 16.12.2019 20:29:38
ну если гранатомет расчехлять то
Изменено: БМВ — 16.12.2019 20:37:38 По вопросам из тем форума, личку не читаю. |
||||||||||||||||
Ігор Гончаренко Пользователь Сообщений: 13746 |
#6 16.12.2019 20:36:42 Выполните Test
Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
||
albert123 Пользователь Сообщений: 16 |
#7 16.12.2019 20:57:34 Спасибо вам большое |
1 / 1 / 0 Регистрация: 27.11.2013 Сообщений: 9 |
|
1 |
|
Получить имя файла без расширения27.11.2013, 15:29. Показов 22987. Ответов 8
Помогите написать код программы. Дана строка содержащая ПОЛНОЕ ИМЯ ФАЙЛА , т.е имя диска, список каталогов ( путь) , собственно имя и расширение. Нужно выделить из этой строки имя файла (без расширения).
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
27.11.2013, 15:29 |
Ответы с готовыми решениями: Получить название файла без расширения
Получить имя файла без расширения Получить имя файла без расширения 8 |
1 / 1 / 0 Регистрация: 27.11.2013 Сообщений: 9 |
|
27.11.2013, 16:32 [ТС] |
2 |
Дана строка содержащая ПОЛНОЕ ИМЯ ФАЙЛА , т.е имя диска, список каталогов ( путь) , собственно имя и расширение. Нужно выделить из этой строки имя файла (без расширения).
0 |
1 / 1 / 0 Регистрация: 27.11.2013 Сообщений: 9 |
|
27.11.2013, 16:38 [ТС] |
3 |
в VBA
0 |
Заблокирован |
||||
27.11.2013, 17:18 |
4 |
|||
Добавлено через 1 минуту
2 |
6875 / 2807 / 533 Регистрация: 19.10.2012 Сообщений: 8,562 |
|
27.11.2013, 17:41 |
5 |
split по application.pathseparator, берём последний элемент, там сплит по точке, откидываем последний элемент.
0 |
Заблокирован |
|
28.11.2013, 08:02 |
6 |
CreateObject(«Scripting.FileSystemObject») В этом объекте и имя и расширение, и папку, и родительскую папку можно получить.. Добавлено через 1 минуту
0 |
Dmitrii 2617 / 547 / 109 Регистрация: 21.03.2012 Сообщений: 1,051 |
||||
28.11.2013, 22:23 |
7 |
|||
… Нужно выделить из этой строки имя файла (без расширения).
0 |
1 / 1 / 0 Регистрация: 27.11.2013 Сообщений: 9 |
|
29.11.2013, 00:03 [ТС] |
8 |
Dmitrii, нужен код программы , который будет начинаться с описания перемененных через Dim «переменная» as Integer
0 |
The trick Модератор 9167 / 3405 / 853 Регистрация: 22.02.2013 Сообщений: 5,185 Записей в блоге: 78 |
||||
29.11.2013, 00:09 |
9 |
|||
Решение
3 |
‘[/vba]
‘ Keep It Simple
‘ .. why use FileSystemObject or Split when Left and Mid will do it
‘ the FSO has some 33 Subs or Functions
that have to be loaded each time it is created.
‘ and needs the file to exist … yet is only a bit slower
… under twice time.. some good code in FSO
‘ conservation is good .. spare a few electrons. ????… save a few millionths of a sec
‘Also
‘ .. why the format of a function that we all seem to use like
‘
‘ .. Function GetAStr(x) as string
‘ dim extraStr as string
‘ a lot of work with extraStr..
‘ that could have been done with the string variable GetAStr
already created by the function
‘ then .. GetAStr=extraStr to put it in its right place
‘ .. End Function
Function GetNameL1$(FilePath$, Optional NLess& = 1)
‘ default Nless=1 => name only
‘ NLess =2 => xcopya.xls xcopyb.xls xcopy7.xlsm all as xcopy to get find latest version
‘ Nless = — 4 or less => name with name.ext worka.xlsm
GetNameL1 = Mid(FilePath, InStrRev(FilePath, «») + 1)
GetNameL1 = Left(GetNameL1, InStrRev(GetNameL1, «.») — NLess)
End Function
Function LastFold$(FilePath$)
LastFold = Left(FilePath, InStrRev(FilePath, «») — 1)
LastFold = Mid(LastFold, InStrRev(LastFold, «») + 1)
End Function
Function LastFoldSA$(FilePath$)
Dim SA$(): SA = Split(FilePath, «»)
LastFoldSA = SA(UBound(SA) — 1)
End Function
[<vba]
В этом руководстве будет показано, как получить и установить имя книги в VBA.
Мы можем получить или установить имя активной книги в VBA или пройти через все открытые книги в Excel и получить или установить имя каждой из них с помощью цикла VBA.
Получить название книги
Чтобы получить имя активной книги, нам нужно использовать свойство name объекта workbooks.
12345 | Sub GetWorkbookName ()Dim strWBName As StringstrWBName = ActiveWorkbook.NameMsgBox strWBNameКонец подписки |
Если бы мы запустили приведенный выше код, мы бы увидели на экране окно сообщения с именем активной книги.
Чтобы просмотреть все активные книги и вернуть имена книг в Excel, мы можем запустить следующий код:
1234567 | Sub GetWorkbookNames ()Dim wb As WorkbookДля каждого ББ в книгахActiveCell = wb.NameActiveCell.Offset (1, 0) .SelectСледующийКонец подписки |
В приведенных выше примерах будет указано расширение файла (например, xlsx). Если вы не хотите включать расширение, мы можем использовать несколько методов, чтобы получить только имя файла книги.
Получить имя книги без расширения
Мы можем использовать функции LEFT и INSTR для удаления любых символов после точки в имени файла:
12345 | Sub GetWorkbookName ()Dim strWBName As StringstrWBName = Left (ActiveWorkbook.Name, InStr (ActiveWorkbook.Name, «.») — 1)MsgBox strWBNameКонец подписки |
Мы можем использовать функции LEFT и LEN, чтобы удалить 5 символов из конца имени файла:
12345 | Sub GetWorkbookName ()Dim strWBName As StringstrWBName = Left (ActiveWorkbook.Name, Len (ActiveWorkbook.Name) — 55)MsgBox strWBNameКонец подписки |
Установка имени книги
Чтобы установить имя книги в VBA, мы по-прежнему используем свойство Name книги, однако мы не можем использовать этот метод для изменения имени активной книги. Это связано с тем, что активная книга открыта, и произойдет ошибка доступа к файлу. Чтобы преодолеть это, мы можем сохранить файл с новым именем, а затем удалить старый файл.
12345678910 | Public Sub SetWorkbookName ()Dim strPath как строкаDim strNewName As StringDim strOldName как строкаstrOldName = ActiveWorkbook.NamestrNewName = InputBox («Введите новое имя книги»)strPath = ActiveWorkbook.PathActiveWorkbook.SaveAs strPath & «/» & strNewNameУбить strPath & «/» & strOldNameКонец подписки |
Чтобы переименовать закрытую книгу, мы можем использовать метод Name.
123 | Общедоступная подпрограмма RenameWorkbook ()Назовите «C: Data MyFile.xlsx» как «C: Data MyNewFile.xlsx»Конец подписки |