Open a workbook without knowing the exact name - excel

so i searched but didnt find something good for my use , i have a folder where i will import an excel file , this excel file will have a different name everytime how i can open it with vba , thank you

You can get the file name using the Dir function and multiple character (*) wildcard.
Const Path As String = "C:\Test"
Dim filename As String
filename = Dir(Path & "\*.xlsx")
If Len(filename) > 0 Then
' Do your work
' Remember 'filename' only holds the file name
' you will need to attach the rest of the path to get the full directory.
End If
Note: If there's only one file in the folder you will not have any issues, however if the folder contains multiple files (matching the above pattern), you will need to either loop or provide additional file name characters to the function.
An example:
File name: daily_report_20190404.xlsx
filename = Dir(Path & "\daily_report_*.xlsx")
Hope this helps.

Related

Add 'sep=' line to the csv file

The problem is, I want to copy data from .csv file, but excel automatically separates it into columns by comma, I need to separate it by ";".Can I edit csv file using vba code to add 'sep=' at the beginning?
Excel/VBA ignores the separator option if the file has the .csv extension. You have to rename it to set the delimiter. Check out my VBA CSV parser project.
The solution worked for me is to use filesystem object to read csv file and copy it into temporary file with 'sep=' at the first line.
Here is the code:
Function readCsvF(delim as String, fPath as String) As String
Dim sourceFile As Object, objFSO as Object, newTempFile as Object, _
line as String, newName as String
Set objFSO = CreateObject("scripting.FileSystemObject")
Set sourceFile = objFSO.OpenTextFile(fPath)
newName = objFSO.GetParentFolderName(fPath) & "\tempCSVfile.csv"
Set newTempFile = objFSO.CreateTextFile(newName, True)
newTempFile.Writeline("sep=" & delim)
While Not sourceFile.AtEndOfStream
line = sourceFile.Readline
newTempFile.Writeline (line)
Wend
sourceFile.Close
newTempFile.Close
readCsvF = newName
End Function
So what this function does is basically creates new file in which writes first line sep=*'your specified delimiter'* and then copies data from original csv file line by line. This function takes two string parameters: delim is delimiter you want to use and fPath is a path to the csv file, - and returns a path to the new file, so you can open it as workbook and do whatever manipulation you want with it.
Hopefully this will help someone, I really struggled to find the solution, maybe there was any better way, idk.

When using the WorkBook.SaveAs method is there a way to get the full file path with extension after creating the file? VBA [duplicate]

Say, I'm writing a VBA inside my excel file sample.xls. Now I want to get the full path of sample.xls in my VBA. How do I do it?
If you mean VBA, then you can use FullName, for example:
strFileFullName = ThisWorkbook.FullName
(updated as considered by the comments: the former used ActiveWorkbook.FullName could more likely be wrong, if other office files may be open(ed) and active. But in case you stored the macro in another file, as mentioned by user #user7296559 here, and really want the file name of the macro-using file, ActiveWorkbook could be the correct choice, if it is guaranteed to be active at execution time.)
this is a simple alternative that gives all responses, Fullname, Path, filename.
Dim FilePath, FileOnly, PathOnly As String
FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
strScriptFullname = WScript.ScriptFullName
strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\"))
If you need path only this is the most straightforward way:
PathOnly = ThisWorkbook.Path
if you need path only without file name:
ActiveWorkbook.Path
it would return D:\Folder
if you need file path with file name also:
ActiveWorkbook.FullName
it would return D:\Folder\sample.xls
if you need file name only:
ActiveWorkbook.Name
it would return sample.xls
so if you want combine file path and file name to get full directory don't forget to add "" between. otherwise its simpler using .Path
ActiveWorkbook.FullName would be better I think, in case you have the VBA Macro stored in another Excel Workbook, but you want to get the details of the Excel you are editing, not where the Macro resides.
If they reside in the same file, then it does not matter, but if they are in different files, and you want the file where the Data is rather than where the Macro is, then ActiveWorkbook is the one to go for, because it deals with both scenarios.
There is a universal way to get this:
Function FileName() As String
FileName = Mid(Application.Caption, 1, InStrRev(Application.Caption, "-") - 2)
End Function

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()

ASP FileObject.Name converting to '?'

I have a script that lists all files in a directory, then for each one it will Response.Write the name and how many downloads it has.
I have everything completed, but when I went for a test, the files that have "odd" characters in the name are replace with a ?
I'm guessing, that since some files have foreign languages as there name, and that some have the iPhone emoji icons in the name, that it doesn't recognize it and puts a ? instead, but this is a serious issue since I can't give the correct file name back to the user, then that incorrect name is fed back into the url to download. (Which doesn't work)
Any suggestions?
Edit:
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fo=fs.GetFolder(Server.MapPath("."))
for each file in fo.files
if fs.GetExtensionName(file.Path) = "plist" then
dim tempList, tempName, ...
tempList = split(file.Name, ".")
'Manipulate name and data ...
Response.write(name)
end if
next
The file names themselves have odd characters, and file.Name returns a ? instead of what is actually there.
18アイコン is one example.
Here's some code which works fine for me:
<%# Language="VBScript" CodePage="65001" %><%
Option Explicit
Response.CodePage = 65001
Response.CharSet = "utf-8"
Dim fs, fo, file
Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set fo = fs.GetFolder(Server.MapPath("."))
For Each file In fo.files
If fs.GetExtensionName(file.Path) = "plist" Then
' Do whatever here...
Response.Write file.Name & "<br>"
End If
Next
%>
If you are using any variables that you didn't dimension beforehand, you'll need to remove the Option Explicit; otherwise, VBScript will complain that you didn't dimension them.
Edit: I copy & pasted the wrong code; this code works.

How to get the excel file name / path in VBA

Say, I'm writing a VBA inside my excel file sample.xls. Now I want to get the full path of sample.xls in my VBA. How do I do it?
If you mean VBA, then you can use FullName, for example:
strFileFullName = ThisWorkbook.FullName
(updated as considered by the comments: the former used ActiveWorkbook.FullName could more likely be wrong, if other office files may be open(ed) and active. But in case you stored the macro in another file, as mentioned by user #user7296559 here, and really want the file name of the macro-using file, ActiveWorkbook could be the correct choice, if it is guaranteed to be active at execution time.)
this is a simple alternative that gives all responses, Fullname, Path, filename.
Dim FilePath, FileOnly, PathOnly As String
FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
strScriptFullname = WScript.ScriptFullName
strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\"))
If you need path only this is the most straightforward way:
PathOnly = ThisWorkbook.Path
if you need path only without file name:
ActiveWorkbook.Path
it would return D:\Folder
if you need file path with file name also:
ActiveWorkbook.FullName
it would return D:\Folder\sample.xls
if you need file name only:
ActiveWorkbook.Name
it would return sample.xls
so if you want combine file path and file name to get full directory don't forget to add "" between. otherwise its simpler using .Path
ActiveWorkbook.FullName would be better I think, in case you have the VBA Macro stored in another Excel Workbook, but you want to get the details of the Excel you are editing, not where the Macro resides.
If they reside in the same file, then it does not matter, but if they are in different files, and you want the file where the Data is rather than where the Macro is, then ActiveWorkbook is the one to go for, because it deals with both scenarios.
There is a universal way to get this:
Function FileName() As String
FileName = Mid(Application.Caption, 1, InStrRev(Application.Caption, "-") - 2)
End Function

Resources