I am trying to select a folder and then assign that path to my file Variant. However, the code stops after the folder is selected and does not go to the next step. What can be wrong? The next step would be 'If selected_folder <> "" Then' but it just stops and debugger goes back to Sub.
Sub sheetCompare2()
Application.ScreenUpdating = False
Dim i As Integer
Dim WS_Count As Integer
Dim mDirs As String
Dim path As String
Dim OutFile As Variant, SrcFile As Variant
Dim file As Variant
Dim wb As Workbook
Dim datevar As Variant
Dim datevar2 As Variant
Dim selected_folder As String
Set wb = ThisWorkbook
WS_Count = ActiveWorkbook.Worksheets.Count
OutFile = ActiveWorkbook.Name
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a Folder"
If Application.FileDialog(msoFileDialogFolderPicker).Show = -1 Then
selected_folder = .SelectedItems(1)
End If
End With
If selected_folder <> "" Then
file = Dir(selected_folder)
End If
While (file <> "")
path = selected_folder + file
Workbooks.Open (path)
SrcFile = ActiveWorkbook.Name
datevar = Right(file, 9)
datevar2 = Left(datevar, 4)
....'and so on
End Sub
Please, try changing this part of the code:
If selected_folder <> "" Then
file = Dir(selected_folder)
End If
While (file <> "")
path = mDirs + file
Workbooks.Open (path)
SrcFile = ActiveWorkbook.Name
datevar = Right(file, 9)
datevar2 = Left(datevar, 4)
'....'and so on
with:
If selected_folder <> "" Then
File = Dir(selected_folder & "\" & "*.xls*")
End If
Do While File <> ""
path = selected_folder & "\" & File
Workbooks.Open (path)
SrcFile = ActiveWorkbook.Name
datevar = Right(File, 9)
datevar2 = left(datevar, 4)
File = Dir
'...
Loop
In order to make Dir return a file name, you must set an extension. At least *.* for iterate between all files. But, wanting to open the files in Excel, it is good to use "*.xls*", as the above code does.
Then, the path of the file to be open should be built as above.
Your code does not show how you redefine File in order to make the loop working. You maybe have File = Dir before the loop end. If not, I added...
Related
I am new to VBA and dont have that much knowledge about coding, Need kind support to open the folder via dialog box instead of giving the source folder path manually in the VBA code (Const FolderA = "Folder Path"). Code works fine with inputting manual path inside the vba code(code copied)
Public Sub MoveFiles()
Const colA = 1
Const colB = 2
Const colC = 3
Const FolderA = "H:\My Drive\Appreciation Certification\Sep 21 2022\QR Code\" ' source folder
Const srcSheet = "Source"
Dim xlS As Excel.Worksheet
Dim xlW As Excel.Workbook
Dim RN As Long ' row number
Dim fName As String
Dim fPath As String
' ready
Set xlW = ActiveWorkbook
Set xlS = xlW.Sheets(srcSheet)
RN = 2
fName = Trim(xlS.Cells(RN, colA).Text)
' run thru ColA until hit a blank
On Error Resume Next ' expect problems if no target Dir
While fName <> ""
' if it hasn't aready been moved
If Trim(xlS.Cells(RN, colC).Text) = "" Then
' got one.
' Get the path. Ensure trailing backslash
fPath = Trim(xlS.Cells(RN, colB).Text)
If Right(fPath, 1) <> "\" Then fPath = fPath & "\"
' if the target already exists, nuke it.
If Dir(fPath & fName) <> "" Then Kill fPath & fName
' move it
FileCopy FolderA & fName, fPath & fName
DoEvents
' report it
If Err.Number <> 0 Then
xlS.Cells(RN, colC).Value = "Failed: Check target Dir"
Err.Clear
Else
xlS.Cells(RN, colC).Value = Now()
End If
End If
' ready for next one
RN = RN + 1
fName = Trim(xlS.Cells(RN, colA).Text)
Wend
MsgBox "All files moved!!"
End Sub
I want copy pdf from source folder and have to paste in destpath based on Excel, help me where I am gone wrong
Sub CheckandSend()
Dim irow As Integer
Dim DestPath As String
Dim SourcePath As String
Dim pfile As String
Dim FSO As Object
Dim Fldr As Object, f As Object
SourcePath = "I:\Mechanical\ExternalProjects\Cummins Emission Systems\35101124 PT Cup Test Rig\16 PDF to Vendor"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Fldr = FSO.GetFolder(SourcePath).Files
DestPath = "P:\CENTRAL PLANNING\PROJECTS 2020-2021\VAM-TARSON\Newfolder1"
irow = 7
Do While Cells(irow, 2) <> Empty
pfile = Dir(SourcePath & "\*" & Cells(irow, 2) & "*")
If pfile <> "" And Right(pfile, 3) = "PDF" Then
FileCopy SourcePath, DestPath
irow = irow + 1
End If
Loop
end sub
You are mixing 2 different methods: The FileSystemObject and Dir(). Only use one of them.
FileCopy SourcePath, DestPath only copies the path but there is no filename.
Directly include the file extension in your Dir() so you don't need to check for pdf files:
FileName = Dir(SourcePath & "*" & ws.Cells(iRow, 2) & "*.pdf")
There may exist more than one file with the key word from your cell. Your code copies randomly one of them. Make sure to loop so you get all of them
Do While FileName <> vbNullString 'if more files with the key word from ws.Cells(iRow, 2) exist copy all of them
VBA.FileCopy SourcePath & pfile, DestPath 'copy needs to be path AND filename
FileName = Dir()
Loop
It could look like this:
Option Explicit
Public Sub CheckandSend()
Dim ws As Worksheet 'make sure to define a sheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim SourcePath As String
SourcePath = "C:\Temp\" 'make sure paths end with \
Dim DestPath As String
DestPath = "P:\CENTRAL PLANNING\PROJECTS 2020-2021\VAM-TARSON\Newfolder1\" 'make sure paths end with \
Dim iRow As Long
iRow = 7
Do While ws.Cells(iRow, 2) <> vbNullString
Dim FileName As String
FileName = Dir(SourcePath & "*" & ws.Cells(iRow, 2) & "*.pdf") 'this will only go through pdf files
Do While FileName <> vbNullString 'if more files with the key word from ws.Cells(iRow, 2) exist copy all of them
VBA.FileCopy SourcePath & pfile, DestPath 'copy needs to be path AND filename
FileName = Dir()
Loop
iRow = iRow + 1
Loop
End Sub
The code below works.
Sub CheckandSend()
' 191
Const Ext As String = ".pdf"
Dim SourcePath As String
Dim DestPath As String
Dim FSO As Object
Dim Fldr As Object
Dim pFile As String
Dim f As Object
Dim iRow As Long ' row numbers should be declared as Long
' both paths must end on backslash ("\")
SourcePath = "I:\Mechanical\ExternalProjects\Cummins Emission Systems\35101124 PT Cup Test Rig\16 PDF to Vendor\"
DestPath = "P:\CENTRAL PLANNING\PROJECTS 2020-2021\VAM-TARSON\Newfolder1\"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Fldr = FSO.GetFolder(SourcePath).Files
' loop until last used cell in column B
For iRow = 7 To Cells(Rows.Count, 2).End(xlUp).Row
pFile = Trim(Cells(iRow, 2).Value)
If Len(pFile) = 0 Then Exit For ' exit at first blank row
If LCase(Right(pFile, 4)) <> Ext Then pFile = pFile & Ext
If Len(Dir(SourcePath & pFile)) Then
FileCopy SourcePath & pFile, DestPath & pFile
End If
Next iRow
End Sub
There are a few inconsistencies in your procedure which I have eliminated. For example, your code isn't clear whether the file name in the worksheet has a pdf extension or not, then looks for any file by that name but rejects all that aren't "pdf". The above code rephrases this to mean that you want a PDF file by the name in the worksheet and any file by the same name but another extension is to be ignored. It's the same, I think, but more efficient if you limit the search to PDF.
The other thing is the end of the loop. Is it when there are no more file names or when a cell is blank? The above code ends in either case. I presume that is OK because there are no blanks in your list of files. If so, it would be better, however, to just skip any accidental blanks and continue until the last line has been processed. If you agree, delete the Exit For and set an End If at the appropriate point (before the Next iRow) and indent all lines in between.
I have vba code to convert a ppt to pptx file, but how do I preserve the file properties (author/created date, modified date, etc)? Here is the vba code that converts the, in this case .ppt file, to a pptx file.
Sub BatchSave()
' Opens each PPT in the target folder and saves as PowerPoint 2007/2010 (.pptx) format
Dim sFolder As String
Dim sPresentationName As String
Dim oPresentation As Presentation
Dim bidpList As Collection
' Select the folder:
Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)
With fDialog
.Title = "Select folder and click OK"
.AllowMultiSelect = False
.InitialView = msoFileDialogViewList
If .Show <> -1 Then
MsgBox "Cancelled By User", , "List Folder Contents"
Exit Sub
End If
sFolder = fDialog.SelectedItems.Item(1)
If Right(sFolder, 1) <> "\" Then sFolder = sFolder + "\"
End With
' Make sure the folder name has a trailing backslash
If Right$(sFolder, 1) <> "\" Then
sFolder = sFolder & "\"
End If
' Are there PPT files there?
If Len(Dir$(sFolder & "*.PPT")) = 0 Then
MsgBox "Bad folder name or no PPT files in folder."
Exit Sub
End If
' Open and save the presentations
sPresentationName = Dir$(sFolder & "*.PPT")
While sPresentationName <> ""
Set oPresentation = Presentations.Open(sFolder & sPresentationName, , ,
False)
Call oPresentation.SaveAs(sFolder & sPresentationName & "x")
oPresentation.Close
Wend
MsgBox "DONE"
End Sub
Declaring object variables for your two presentations will simplify the code a bit, and then you can do something along these lines:
Dim oPres As Presentation
Dim oCopyPres As Presentation
Dim x As Long
Set oPres = ActivePresentation
ActivePresentation.SaveCopyAs "c:\temp\test.pptx"
Set oCopyPres = Presentations.Open("c:\temp\test.pptx")
On Error Resume Next
For x = 1 To oPres.BuiltInDocumentProperties.Count
oCopyPres.BuiltInDocumentProperties(x).Name = oPres.BuiltInDocumentProperties(x).Name
oCopyPres.BuiltInDocumentProperties(x).Value = oPres.BuiltInDocumentProperties(x).Value
Next
You'll want to modify this to set WithWindow false and to use variables as file names, but you're already doing that in the code you have. It should be simple enough to fold in a modified version of the code above.
I really hope someone can help with this. At the moment I am using vba to import each line of text from a text file into a new column on one row. And each time I run the function a new row of data is created below the previous.
Results:
Row 1 (Showing Data from TextFile 1)
Column A Column B Column C
Data Data Data
Row 2 (Showing Data from TextFile 2)
Column A Column B Column C
Data Data Data
So this all works fine and after I have imported the text from the file, the file is moved from my directory 'unactioned' to a directory called 'actioned'.
So at the moment my code is not quite there yet, I am currently having to define the text file name so that I can import the data from the text file into my spreadsheet and again i am defining the text file name i want to move, this code will only currently work for 1 text file. However what i want to be able to do is if there are several text files in my folder 'unactioned', then i want to import each of these text files into a new row, and move all the text files we have just imported the data from to my folder 'actioned' at the same time
Here is my code:
Sub ImportFile()
Dim rowCount As Long
rowCount = ActiveSheet.UsedRange.Rows.Count + 1
If Cells(1, 1).Value = "" Then rowCount = 1
Close #1
Open "Y:\Incident Logs\Unactioned\INSC89JH.txt" For Input As #1
A = 1
Do While Not EOF(1)
Line Input #1, TextLine
Cells(rowCount, A) = TextLine
A = A + 1
Loop
Close #1
Dim d As String, ext, x
Dim srcPath As String, destPath As String, srcFile As String
srcPath = "Y:\Incident Logs\Unactioned\"
destPath = "Y:\Incident Logs\Actioned\"
ext = Array("*.txt", "*.xls")
For Each x In ext
d = Dir(srcPath & x)
Do While d <> ""
srcFile = srcPath & d
FileCopy srcFile, destPath & d
Kill srcFile
d = Dir
Loop
Next
End Sub
please can someone show me how i would amend this code to do what i need it to do? Thanks in advance
I would suggest breaking your code into multiple functions.
You can change the ImportFile method to not kill ALL files, but just the file it operates on, and then have it take a specific file to operate on one at a time. E.g.:
Sub ImportFile(directory As String, filename As String)
Dim rowCount As Long
rowCount = ActiveSheet.UsedRange.Rows.Count + 1
If Cells(1, 1).Value = "" Then rowCount = 1
Close #1
Open directory & filename For Input As #1
A = 1
Do While Not EOF(1)
Line Input #1, TextLine
Cells(rowCount, A) = TextLine
A = A + 1
Loop
Close #1
'Move the file and delete it
Dim srcPath As String, destPath As String
srcPath = directory & filename
destPath = "C:\Incident Logs\Actioned\" & filename
FileCopy srcPath, destPath
Kill srcPath
End Sub
Then, here is another stackoverflow post on how to iterate files in a folder
So with a little adaptation you could have something like:
Sub ImportAllFiles()
ImportFilesWithExtension "*.txt"
ImportFilesWithExtension "*.xls*"
End Sub
Sub ImportFilesWithExtension(extension As String)
Dim StrFile As String, myDir As String
myDir = "C:\Incident Logs\Unactioned\"
StrFile = Dir(myDir & extension)
Do While Len(StrFile) > 0
ImportFile myDir, StrFile
StrFile = Dir
Loop
End Sub
I'd also break it down into functions:
Sub ImportFile()
Dim rLastCell As Range
Dim vFolder As Variant
Dim vFile As Variant
Dim colFiles As Collection
With ThisWorkbook.Worksheets("Sheet1") 'Note - update sheet name.
'First find the last cell on the named sheet.
Set rLastCell = .Cells.Find( _
What:="*", _
LookIn:=xlValues, _
SearchDirection:=xlPrevious)
If rLastCell Is Nothing Then
'Set LastCell to A2.
Set rLastCell = .Cells(2, 1)
Else
'Set LastCell to column A, last row + 1
Set rLastCell = .Range(rLastCell.Row + 1, 1)
End If
vFolder = GetFolder()
Set colFiles = New Collection
EnumerateFiles vFolder, "\*.txt", colFiles
For Each vFile In colFiles
'Do stuff with the file.
'Close the file and move it.
MoveFile CStr(vFile), "S:\Bartrup-CookD\Text 1\" & Mid(vFile, InStrRev(vFile, "\") + 1, Len(vFile)) 'Note - update folder name.
Next vFile
End With
End Sub
This will place all files into a collection:
Sub EnumerateFiles(ByVal sDirectory As String, _
ByVal sFileSpec As String, _
ByRef cCollection As Collection)
Dim sTemp As String
sTemp = Dir$(sDirectory & sFileSpec)
Do While Len(sTemp) > 0
cCollection.Add sDirectory & "\" & sTemp
sTemp = Dir$
Loop
End Sub
This will ask you to select a folder:
' To Use : vFolder = GetFolder()
' : vFolder = GetFolder("S:\Bartrup-CookD\Customer Services Phone Reports")
Function GetFolder(Optional startFolder As Variant = -1) As Variant
Dim fldr As FileDialog
Dim vItem As Variant
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
If startFolder = -1 Then
.InitialFileName = Application.DefaultFilePath
Else
If Right(startFolder, 1) <> "\" Then
.InitialFileName = startFolder & "\"
Else
.InitialFileName = startFolder
End If
End If
If .Show <> -1 Then GoTo NextCode
vItem = .SelectedItems(1)
End With
NextCode:
GetFolder = vItem
Set fldr = Nothing
End Function
This will move a file from folder A to folder B:
'----------------------------------------------------------------------
' MoveFile
'
' Moves the file from FromFile to ToFile.
' Returns True if it was successful.
'----------------------------------------------------------------------
Public Function MoveFile(FromFile As String, ToFile As String) As Boolean
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
objFSO.MoveFile FromFile, ToFile
MoveFile = (Err.Number = 0)
Err.Clear
End Function
I have the following code which pulls the file names from the directory I specify. I found it on the internet and modified it to work for what I need.
The problem is that I don't want it to popup with a window asking me to pick a folder - I want to use the specified folder. How can I change this code so that I don't have to use the window, or if I can't change it, what can I do about my situation?
Dim xRow As Long
Dim xDirect$, xFname$, InitialFoldr$
InitialFoldr$ = "C:\Desktop" '<<< Startup folder to begin searching from
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder to list Files from"
.InitialFileName = InitialFoldr$
.Show
If .SelectedItems.count <> 0 Then
xDirect$ = .SelectedItems(1) & "\"
xFname$ = Dir(xDirect$, 7)
Do While xFname$ <> ""
ActiveCell.Offset(xRow) = Left(xFname$, InStrRev(xFname$, ".") - 1)
xRow = xRow + 1
xFname$ = Dir
Loop
End If
End With
I ended up changing my code completely and not using the old code. Again, I found some code on the internet and modified it to work for what I need.
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim FileArray() As Variant
Dim FileCount As Integer
Dim FileName As String
Dim rng As Range
Dim Idx As Integer
FileCount = 0
FileName = Dir("C:\Desktop")
' Loop until no more matching files are found
Do While FileName <> ""
FileCount = FileCount + 1
ReDim Preserve FileArray(1 To FileCount)
FileArray(FileCount) = FileName
FileName = Dir()
Loop
GetFileList = FileArray
Set rng = ActiveCell
For Idx = 0 To FileCount - 1
ActiveCell.Offset(Idx, 0).Value = Left(FileArray(Idx + 1), InStrRev(FileArray(Idx + 1), ".") - 1)
Next Idx
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
This is the critical part of the code:
xDirect$ = .SelectedItems(1) & "\"
xFname$ = Dir(xDirect$, 7)
Do While xFname$ <> ""
ActiveCell.Offset(xRow) = Left(xFname$, InStrRev(xFname$, ".") - 1)
xRow = xRow + 1
xFname$ = Dir
Loop
if you change the first line in that block to be
xDirect$ = My_Path_With_Trailing_Slash
you can specify any path you want
On my Excel-2010 the Kelsius's example works only with trailing (right) backslash in the directory name:
FileName = Dir("C:\Desktop\")
This is my full example:
Public Sub ReadFileList()
Dim bkp As String
Dim FileArray() As Variant
Dim FileCount As Integer
Dim FileName As String
Dim Idx As Integer
Dim rng As Range
bkp = "E:\Flak\TRGRES\1\"
If bkp <> "" Then
FileCount = 0
FileName = dir(bkp)
Do While FileName <> ""
Debug.Print FileName
FileCount = FileCount + 1
ReDim Preserve FileArray(1 To FileCount)
FileArray(FileCount) = FileName
FileName = dir()
Loop
End If
End Sub