PDA

View Full Version : How to read own filename



robert32
02-25-2012, 06:17 AM
Hi,

I'm trying to write a VBA script so I can read the filename of the document that is executing the code.

Please can anyone point me in the right direction?



Cheers,

Rob.

p45cal
02-25-2012, 06:26 AM
Thisworkbook.name
thisworkbook.fullname

robert32
02-25-2012, 06:28 AM
Cheers dude!

robert32
02-25-2012, 06:38 AM
One quick further question... is there a function to return the filename without the extension? If not, I can write my own code to achieve this.

shrivallabha
02-25-2012, 06:52 AM
The post came blank....

You need to select the right "ThisDocument" which would be:
Project Explorer | Project(Your Document Name) | Microsoft Word Objects | ThisDocument

Paul_Hossler
02-25-2012, 07:31 AM
no built in VBAfunction (AFAIK) but it's easy enough


Function RemoveExt(sFile As String) As String
Dim i As Long

i = InStrRev(sFile, ".")
RemoveExt = sFile
If i > 0 Then RemoveExt = Left(sFile, i - 1)
End Function
Sub test()
MsgBox RemoveExt(ThisWorkbook.FullName)
MsgBox RemoveExt(ThisWorkbook.Name)
End Sub


Paul

Kenneth Hobs
02-25-2012, 06:23 PM
If you like fso:

Sub Test_GetBaseName()
MsgBox ThisWorkbook.Name, vbInformation, GetBaseName(ThisWorkbook.Name)
End Sub

Function GetBaseName(filespec As String) As String
Dim fso As Object, s As String
Set fso = CreateObject("Scripting.FileSystemObject")
s = fso.GetBaseName(filespec)
Set fso = Nothing
GetBaseName = s
End Function