my code keeps getting a bad file name or number error and I can't figure out what the issue is, any help would be appreciated! I'm trying to store the filepath based on user selection as a variable which I can reference later in a vlookup. Below is my code, I can't figure out what's wrong but I used the pasted code in another macro which compiled fine.
sub edits
dim xpath and xfile as string
xPath = NewPath 'Newpath function executes
xfile = Dir$(xPath & "*.xlsm*", vbNormal) 'error here
Set SourceBook = Workbooks.Open(xPath & xfile)
End Sub
Function NewPath() As String
With Application.FileDialog(msoFileDialogOpen)
.ButtonName = "Choose a file"
.Title = "Previous File"
.AllowMultiSelect = False
If .Show Then xPath = .SelectedItems(1) & "\"
End With
End Function
Below is the code I've used which has compiled, it has the user select a folder instead of a file
sub something
dim xpath and xfile as string
xPath = NewPath
If Not strPath = vbNullString Then
xfile = Dir$(xPath & "*.xlsm", vbNormal)
Do While Not xfile = vbNullString
'some code
Set SourceBook = Workbooks.Open(xPath & xfile)
SourceBook.Close False
xfile = Dir$()
Loop
End If
End Sub
Function NewPath() As String
With Application.FileDialog(msoFileDialogFolderPicker)
.ButtonName = "Choose a folder"
.Title = "Folder Picker"
.AllowMultiSelect = False
If .Show Then NewPath = .SelectedItems(1) & "\"
End With
End Function
Related
I don't see any parameter in GetOpenFilename to set default folder to Downloads.
Currently, it opens Documents folder. Is it possible to make the default location as Downloads folder.
I can't hardcode the path as Downloads without including the Username.
e.g C:\Users\NameOfUser\Downloads
**********Solution**********
Dim FilePaths As FileDialogSelectedItems
Dim iFolderPath As String
iFolderPath = Environ("USERPROFILE") _
& Application.PathSeparator & "Downloads" & Application.PathSeparator
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = True
.Filters.Clear
.Filters.Add "Open CSV", "*.csv"
.InitialFileName = iFolderPath
If .Show <> -1 Then
Do
ans = MsgBox("No file selected. Cannot continue.", 53, "Try again")
If ans = 2 Then Exit Do
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = True
.Filters.Clear
.Filters.Add "Open CSV", "*.csv"
.InitialFileName = iFolderPath
.Show
End With
Loop
If ans = 2 Then MsgBox "No file selected. User cancelled.", vbInformation, "Special"
Exit Sub
End If
Set FilePaths = .SelectedItems
End With
Dim FilePath As Variant
For Each FilePath In FilePaths
Workbooks.Open FilePath
Next FilePath
Choose Files to Open (FileDialog)
Here is a different way that uses the FileDialog object.
Use the Environ function to build the initial path.
Sub ChooseFilesToOpen()
Dim iFolderPath As String: iFolderPath = Environ("USERPROFILE") _
& Application.PathSeparator & "Downloads" & Application.PathSeparator
Dim FilePaths As FileDialogSelectedItems
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = True
.Filters.Clear
.Filters.Add "Excel Workbook", "*.xlsx"
.InitialFileName = iFolderPath
If .Show <> -1 Then
MsgBox "Canceled.", vbExclamation
Exit Sub
End If
Set FilePaths = .SelectedItems
End With
Dim FilePath As Variant
For Each FilePath In FilePaths
Debug.Print FilePath
Next FilePath
End Sub
I am trying to loop through all the 'xlsx' files in a folder and convert them to 'xls' ( Excel 97-2003 Worksheet) format. I use the following codes but then the output files are still saved as 'xlsx' instead of 'xls'. I am a beginner and looking to learn more from others. Thanks for your help!
Sub Convert()
Dim strPath As String
Dim strFile As String
Dim strfilenew As String
Dim xWbk As Workbook
Dim xSFD, xRFD As FileDialog
Dim xSPath As String
Dim xRPath As String
Set xSFD = Application.FileDialog(msoFileDialogFolderPicker)
With xSFD
.Title = "Please select the folder contains the xls files:"
.InitialFileName = "C:\"
End With
If xSFD.Show <> -1 Then Exit Sub
xSPath = xSFD.SelectedItems.Item(1)
Set xRFD = Application.FileDialog(msoFileDialogFolderPicker)
With xRFD
.Title = "Please select a folder for outputting the new files:"
.InitialFileName = "C:\"
End With
If xRFD.Show <> -1 Then Exit Sub
xRPath = xRFD.SelectedItems.Item(1) & "\"
strPath = xSPath & "\"
strFile = Dir(strPath & "*.xlsx")
strfilenew = Dir(strPath & "*.xls")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While strFile <> ""
If Right(strFile, 4) = "xlsx" Then
Set xWbk = Workbooks.Open(Filename:=strPath & strfilenew)
xWbk.SaveAs Filename:=xRPath & strfilenew, _
FileFormat:=xlExcel18
xWbk.Close SaveChanges:=True
End If
strFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
There was a bit of a mix-up in your file naming, basically as evidenced by the several double-declarations that I removed. The really big mistake was here, Set xWbk = Workbooks.Open(Filename:=strPath & strfilenew) where you tried to open the old workbook by the new name. I think the confusion started here "Please select the folder contains the xls files:". Of course, this is the folder with the XLSX files. The recommended antidote is to use "meaningful" variable names but you chose to speak in riddles (like xSFD) which makes coding more difficult.
However, the code below is largely yours, and it does work.
Sub Convert()
' 230
Dim Spath As String ' path to read from (XLSX files)
Dim Rpath As String ' path to write to (XLS files)
Dim strFile As String ' loop variable: current file name
Dim Wbk As Workbook ' loop object: current workbook(strFile)
Dim Sp() As String ' split array of strFile
Dim strFileNew As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select the folder contains the XLSX files:"
.InitialFileName = "C:\"
If .Show <> -1 Then Exit Sub
Spath = .SelectedItems.Item(1) & "\"
End With
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder for outputting the new files:"
.InitialFileName = "C:\"
If .Show <> -1 Then Exit Sub
Rpath = .SelectedItems.Item(1) & "\"
End With
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
strFile = Dir(Spath & "*.xlsx")
Do While strFile <> ""
If Right(strFile, 4) = "xlsx" Then
Sp = Split(strFile, ".")
Sp(UBound(Sp)) = "xls"
strFileNew = Join(Sp, ".")
Set Wbk = Workbooks.Open(Filename:=Spath & strFile)
Wbk.SaveAs Filename:=Rpath & strFileNew, FileFormat:=xlExcel8
Wbk.Close SaveChanges:=True
End If
strFile = Dir
Loop
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub
Observe that the new file name is created by splitting the old name on periods, changing the last element, and reassembling the modified array.
How do I programmatically change the file name of a .txt using excel vba, I need a script where it will go through a folder which consists of txt files and remove time from its filename.
Original Filename: ABC_ABCDE_ABCD_YYYYMMDDTTTTTT.txt
New Filename: ABC_ABCDE_ABCD_YYYYMMDD.txt
Thank you in advance
Mike
As per My understanding of your question, I write a code which asks a user to select the folder and rename ".txt" file as per requirements, you may be add an additional code of line for perfect work
'call sub LoopThroughFiles
'this sub is loop every file and rename it
Sub LoopThroughFiles()
Dim txtfile As String, folderPath As String
Dim newName As String
folderPath = GetFolder()
txtfile = Dir(folderPath & "\" & "*.txt")
While txtfile <> ""
If checkFormat(txtfile) = True Then
newName = Left(txtfile, 23) & ".txt"
On Error Resume Next
'rename file is done here
If Not txtfile = "" Then Name (folderPath + "\" + txtfile) As (folderPath + "\" + newName)
On Error GoTo 0
End If
txtfile = Dir
Wend
End Sub
'this function is for check format of file
'you may edit it as per your requirment
Function checkFormat(str As String) As Boolean
checkFormat = False
If Len(str) = 33 And Mid(str, 4, 1) = "_" Then
checkFormat = True
End If
End Function
'this function for select folder path
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Before use this code please make an additional copy of your file in case some error you have a backup...
Hope This help
I'm trying to display where a file is saved in a message box with the following code:
Sub export()
Dim MyPath As String
Dim MyFileName As String
MyFileName = "MyFileName"
Worksheets("Tab").Copy
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = "Path"
If .Show = -1 Then
GoTo Nextcode1
Else
GoTo Nextcode2
End If
MyPath = .SelectedItems(1) & "\"
End With
Nextcode1:
Block of codes that deals with existing file name.
GoTo Nextcode3
Nextcode2:
Block of codes that deals with cancel.
GoTo Nextcode4
NextCode3:
Application.DisplayAlerts = False
With ActiveWorkbook
.SaveAs fileName:=MyPath & MyFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
Application.DisplayAlerts = True
Worksheets("OtherTab").Activate
MsgBox ("The tab has been exported to " & MyPath & MyFileName & ".")
GoTo NextCode4
NextCode4:
End Sub
However, the message box only displays
The tab has been exported to MyFileName.
With MyPath completely omitted. I tried the following codes
PathName = MyPath & MyFileName
MsgBox ("The tab has been exported to " & PathName & ".")
And
Cstr(MyPath)
MsgBox ("The tab has been exported to " & MyPath & MyFileName & ".")
To no avail. My suspicion is that path name obtained from the msoFileDialogFolderPicker is not a string object but I'm not sure how to deal with it. Help is appreciated!
Ok my bad. The
MyPath = .SelectedItems(1) & "\"
line should have gone under
If .Show = -1 Then
I'm trying to create a list of file names in folder for reference, The following code is listing all the file names with extension Filename.pdf
how do I exclude the extension from file name? .pdf
Option Explicit
Sub GetFileName()
Dim xlRow As Long
Dim sDir As String
Dim FileName As String
Dim sFolder As String
sFolder = "C:\Temp\"
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder"
.InitialFileName = sFolder
.Show
If .SelectedItems.Count <> 0 Then
sDir = .SelectedItems(1) & "\"
FileName = Dir(sDir, 7)
Do While FileName <> ""
Range("A1").Offset(xlRow) = FileName
xlRow = xlRow + 1
FileName = Dir
Loop
End If
End With
End Sub
I'm not 100% sure what you are asking, but I think that
If FileName Like "*.pdf" Then
Range("A1").Offset(xlRow) = Mid(FileName,1,Len(FileName)-4)
End If
might be what you are after.
If the filename itself does not contain a period, you can use Split():
Option Explicit
Sub GetFileName()
Dim xlRow As Long
Dim sDir As String
Dim FileName As String
Dim sFolder As String
sFolder = "C:\Temp\"
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder"
.InitialFileName = sFolder
.Show
If .SelectedItems.Count <> 0 Then
sDir = .SelectedItems(1) & "\"
FileName = Dir(sDir, 7)
Do While FileName <> ""
Range("A1").Offset(xlRow) = Split(FileName, ".")(0)
xlRow = xlRow + 1
FileName = Dir
Loop
End If
End With
End Sub