How to remove file extension from file name (VBA) - excel

I have a filename variable that contains : "Filename.csv" . To extract the filename from a path I use: Filename=Dir([fStr]) where fStr is retrieved from the file that I selected.
I only need the filename without ".csv". How do I remove the ".csv" extension?

It's best to use a function like GetBaseName() instead of relying on functions to replace text. Windows allows periods to appear within the base filename so something like this is legitimate:
My .csv for Bob.csv
Using Replace() would result in:
My for Bob
Not what you're looking for. A better approach would be:
Filename = CreateObject("Scripting.FileSystemObject").GetBaseName(fStr)

You can use the replace function:
Filename = replace(Dir([fStr]),".csv","")

Too late to answer it, might be helpful for future
Try this
Mid(fileName, 1, InStr(1, fileName, ".") - 1)
It will work with any file extension or filename
For example:
fileName : ThisIsMyFile.csv

My code runs on various systems which may not allow scripting. I rewrote this to get around this limitation.
Function FileGetBaseNameNoExt(aFilenameStr As String) As String
Dim TmpCnt As Integer
Dim TmpStr As String
FileGetBaseNameNoExt = aFilenameStr
If InStr(aFilenameStr, ".") = False Then
Exit Function
End If
TmpCnt = 1
TmpStr = Left(Right(aFilenameStr, TmpCnt), 1)
While TmpStr <> "."
TmpCnt = TmpCnt + 1
TmpStr = Left(Right(aFilenameStr, TmpCnt), 1)
Wend
'Make Sure the Filename is Not Something Odd like .csv
If TmpCnt < Len(aFilenameStr) Then
FileGetBaseNameNoExt = Left(aFilenameStr, Len(aFilenameStr) - TmpCnt)
End If
End Function

Related

Lotus Notes external doc files search text

By using the follow code i can find a strin in eny external file ( .txt ).
Function "funcCheckIfStrinInFileExist" use Instr function to find position of the string
and return 0 if an integer if string exist in myRecord (see bellow ).
Is there any way to search a .doc file (or .docx) , because (or .PDF !!!) if file is word document return error.
Thanks in advance.
Do While fileName$ <> ""
varCheckIfStrinInFileExist = funcCheckIfStrinInFileExist( fileName, myString )
If varCheckIfStrinInFileExist Then
Messagebox "i found the text in file : " + fileName
End If
fileName$ = Dir$()
Loop
'************************************************************************
funcCheckIfStrinInFileExist ( fileName, myString ) as integer
.......................................
Do Until Eof(filenum%)
'Read a line of data
Input #filenum%, myRecord
positionOfChar = Instr(myRecord$, varString)
If Cint(positionOfChar) > 0 Then
funcCheckIfStrinInFileExist = True
Close filenum
Exit Function
End If
Loop

How to know numerically the last saved file name

I am creating and saving .ini files in Excel. The files need to follow a specific naming convention that increments by 1 each time a file is created. Not all the files will be created in Excel, some will be done in a separate program. Is there a way to read the saved files in their folder to know which number is next?
For example there are files named exampleFile1.ini through exampleFile63.ini. From Excel using VBA or other means can I see that exampleFile63.ini was the last file and name the next exampleFile64.ini?
Thank you. I'm very new if thats not obvious.
This function will return the next available .INI file name:
Private Function GetNextFile() As String
Dim i As Long
Dim fileName As String
For i = 1 To 1000
' Update Path and File Name prefix below to where your .INI files will be stored.
fileName = "d:\path\exampleFile" & i & ".ini"
If Dir(fileName) = "" Then
GetNextFile = fileName
Exit Function
End If
Next
End Function
Call it like this:
Dim NextIniFile As String
NextIniFile = GetNextFile()

How do I extract a portion of a file name in VBA?

I need to extract a portion of a file name from the filepath.
My macro needs to be able to handle paths/names of varying length, but the porition of the file name I want always starts at the same place; I need to extract the portion of just the filename starting 14 characters in from the beginning and ending before the file extension (excluding the ".").
For example, I want my macro to extract the text "Fixed Table" from the following path name:
C:\Users\m.jones\Desktop\New folder (2)\LS4102-104-01 Fixed Table.slddrw
EDIT:
I just experimented with this, and the code below seems to work. Is this a valid approach, or am I going to run in to issues?
PartNoDes = Mid(swDraw.GetPathName, InStrRev(swDraw.GetPathName, "\") + 1)
PartNoDes = Right(PartNoDes, Len(PartNoDes) - 14)
PartNoDes = Left(PartNoDes, Len(PartNoDes) - 7)
You can use a FileSystemObject to get the base filename (i.e., the filename without extension) and then use Mid() to extract a portion of it.
Const strFile As String = "C:\Users\m.jones\Desktop\New folder (2)\LS4102-104-01 Fixed Table.slddrw"
With CreateObject("Scripting.FileSystemObject")
Debug.Print Mid$(.GetBaseName(strFile), 14) ' => "Fixed Table"
End With
This method should be preferred over string parsing that looks for \ and . because filenames may contain periods that aren't part of the extension.
I would recommend using built in functions (e.g. MID() and INSTRREV()) over creating external objects to do what you want.
The "answer" you posted is on the right track - though since you posted it in the form of a question, I think it would have been better served as an edit to your original question.
To answer your answer-question:
Is the approach valid? Yes.
Will you run into issues? For this application - probably not. But I would advise against hardcoding the number of characters in the extension. I don't see Solidworks changing their drawing extension anytime soon - but it's possible (e.g. look at Microsoft: .xls to .xlsx, etc.) and it limits your ability to deal with other extensions (e.g. .Slpdrt, .Sldasm, etc. )
Also, I would cast swDraw.GetPathName to a variable to lower the overhead of repeatedly calling that function on the swDraw COM object.
E.g.
Dim FilePath as String
FilePath= swDraw.GetPathName
You can do what you want in one line:
Mid(FilePath, InStrRev(FilePath, "\") + 14, InStrRev(FilePath, ".") - InStrRev(FilePath, "\") - 14)
Test:
Sub QuickTest()
Const FilePath= "C:\Users\m.jones\Desktop\New folder (2)\LS4102-104-01 Fixed Table.slddrw"
MsgBox Mid(FilePath, InStrRev(FilePath, "\") + 14, InStrRev(FilePath, ".") - InStrRev(FilePath, "\") - 14)
End Sub
You can make it easier to read using variables:
Sub QuickTest()
Const FilePath= "C:\Users\m.jones\Desktop\New folder (2)\LS4102-104-01 Fixed Table.slddrw"
Dim MidStart As Long
MidStart = InStrRev(FilePath, "\") + 14
Dim MidEnd As Long
MidEnd = InStrRev(FilePath, ".")
Dim MyText As String
MyText = Mid(FilePath, MidStart, MidEnd - MidStart)
MsgBox MyText
End Sub
Perhaps this will do what you want, uses Split then takes portions of the resulting array, uses ubound to make sure we have the last instance of a slash and full stop, this negates any issues with full stops being in the name or any levels of directory tree:
Sub FileChop()
Dim MyString As String, FileChop As String
'MyString = "C:\Users\m.jones\Desktop\New folder (2)\LS4102-104-01 Fixed Table.slddrw"
MyString = "LS4102-104-01 Mr. Smith.slddrw"
FileChop = Mid(Split(MyString, "\")(UBound(Split(MyString, "\"))), 14, 100) 'Including extension
MsgBox FileChop
FileChop = Left(FileChop, (Len(FileChop) - 1) - Len(Split(FileChop, ".")(UBound(Split(FileChop, "."))))) 'Excluding extension
MsgBox FileChop
End Sub
I know this does not directly answer your question, but SolidWorks provides access to VSTA which uses .NET libraries, which in turn are significantly more powerful than VBA. When you create your macro, there is an option from the pulldown menu for VSTA in VB or C#.
In that case, you could simply use
Imports System.IO
Dim PathName as string = Path.GetFilePath(swModelDoc2.GetPathName)
or
Dim PathName as string = Path.GetFileNameWithoutExtension(swModelDoc2.GetPathName)

CSV quotes + comma separators and BREAK LINE : import in EXCELwithout break line

I have this kind of CSV :
So when I import in EXCEL 2013 with "get data from text file",
1) how to say separator IS QUOTES + COMMA,
2) For Excel, BREAK LINE in fields are new line of data... how to say it's not ?
I know that CSV are a long topic on the Web, but there is no obvious solution.
So thanks for your help.
Step 1: I would first fix the file:
Sub ImportData()
Dim dataTextFile As String
Dim outTextFile As String, splitPart As String, missingPart As String, ret As String
'---Read the file---
Open "C:\Data.txt" For Input As #1
dataTextFile = Input$(LOF(1), 1)
Close #1
dataTextFile = Replace(dataTextFile, vbNewLine, "[NEW_LINE]")
ret = GetRegex("(.*?,.*?,.*?),")
outTextFile = outTextFile & ret & vbNewLine
Do While 1
If (ret = GetRegex(dataTextFile, ",(.*?,.*?,.*?)")) <> "" Then
Exit Do
Else
outTextFile = outTextFile & ret & vbNewLine
dataTextFile = Right(dataTextFile, Len(dataTextFile) - Len(ret))
End If
Loop
'---Write back to the file---
Open "C:\Data.txt" For Output As #1
Write #1, outTextFile
Close #1
End Sub
You can find the GetRegex function here: link. Or just use the general Regex object. Warning: I haven't tested the code so you might need to do some tinkering.
Step 2: Next you simply import the file normally via the Import Wizard as comma separated file.
Step 3: Lastly replace "[NEW_LINE]" with New Line characters via macro or whatever other way.
Alternatively you may just as well do steps 2-3 in the same macro - and use the Right function or a Regex to extract the column to your output worksheet.

How do I delete "filename.txt" in "blah\bleurgh\filename.txt" in VBS?

such a silly question I know, but I want to remove the filename in a string such as
"blah\bleurgh\filename.txt"
To delete the extension I would do
strFile = Left(strFile, InStrRev(strFile, ".") - 1)
But doing similiar to delete the filename at the end does nothing, e.g.
tempStrFile = Left(tempStrFile, InStrRev(tempStrFile, "\") - 1)
A "\\" doesn't work either, incase it was an escape character issue.
Many thanks!
edit: for further information what I want to do is if given a filename such as "filename.txt" I want to output "output_filename.csv" - I have no problems with this.
If I get a directory though such as "blah\filename.txt" I have difficulty sticking output in the middle to get "blah\output_filename.csv"
If I understand what you want, then your code works for me, the following code:
dim tempStrFile
tempStrFile = "blah\bleurgh\filename.txt"
tempStrFile = Left(tempStrFile, InStrRev(tempStrFile, "\") - 1)
tempStrFile = tempStrFile & "\output_filename.csv"
msgbox tempStrFile
will output blah\bleurgh\output_filename.csv which I belive is what you want.

Resources