Name of the file inside the excel file cell using VBA - vba

I need a VBA where it updates the "name of the excel file" inside that particular "excel file". There are 12 files in the folder. The path for this folder is D:\Amit. Name of those 12 files are "Cash Report as on 11-05-2017 0000Hrs" starting from Midnight (that's why 0000Hrs) and it increases by 2 hours making it 0200Hrs, 0400Hrs etc. We prepare these files daily after every 2 hours. Sometimes it does happen that we run the file after 3 hours making it 0500Hrs instead of 0400Hrs just after 0200Hrs. What I need is a VBA file which opens all these 12 files and in column A in the last row of each respective file, it mentions the name of that particular file.
Eg. it should open all 12 files and then in the first file named Cash Report as on 11-05-2017, in the last row of column A of this file - it should mention the name of this particular file.
So if the VBA opened file "Cash Report as on 11-05-2017 0400Hrs" then in the last cell of the column A just after the text or data in the cell, using offset the very below blank cell should have the name of this file as "Cash Report as on 11-05-2017 0000Hrs". Likewise, need something like this for all the files which open up each individual file and update the respective file name inside the last row of column A.
I was trying some of the codes but it's still in bits and pieces.
Dim Source As String
Dim StrFile As String
'do not forget the last backslash in the source directory.
Source = "C:\Users\Admin\Desktop\VBA\"
StrFile = Dir(Source)
Do While Len(StrFile) > 0
Workbooks.Open Filename:=Source & StrFile
StrFile = Dir()
Loop
fldr = Activeworkbook.Path
Dt = Application.InputBox("Enter Date as 'dd-mm-yyyy' ", format(Now," dd-mm-yyyy"
Workbooks.open Filename:= fldr & "\Cash Report as on" & 0400 & "Hrs.xlsx"
Range("A1").End(xlDown).Select
Offset(1).Select

Try This
Sub t()
Dim Source As String
Dim StrFile As String
Dim wb As Workbook
'do not forget last backslash in source directory.
Source = "C:\Users\Admin\Desktop\VBA\"
StrFile = Dir(Source)
Do While Len(StrFile) > 0
Set wb = Workbooks.Open(Source & StrFile)
wb.ActiveSheet.Range("A" & Rows.Count).End(xlUp).Offset(1, 0) = wb.Name
StrFile = Dir()
wb.Close (True)
Loop
End Sub

Try something like this.
Assumptions:
The Excel file name will be pasted always in the first Sheet - in case the specific sheets are naming always in the same way change lines Sheets(1) with Sheets("YourName")
Every row in table from column A in Sheets(1) is not empty as I'm using COUNTA function (thx #Darren Bartrup-Cook)
Code:
Sub InsertFileName()
Dim strFolderPath As String
Dim lngLastRow As Long
Dim FileName As String
Dim WorkBk As Workbook
Dim ErrNumbers As Integer
'Choose folder with Excel files
strFolderPath = GetFolder(ThisWorkbook.Path) & "\"
'Loop through all Excel files in FolderPath
FileName = Dir(strFolderPath & "*.xl*")
Do While FileName <> ""
'Open Excel file
Set WorkBk = Workbooks.Open(strFolderPath & FileName)
'Find the last row in A column
On Error Resume Next
lngLastRow = Application.WorksheetFunction.CountA(WorkBk.Sheets(1).Range("A:A")) + 1
If lngLastRow = 1 Then
ErrNumbers = ErrNumbers + 1
Err.Clear
GoTo NextWkb
End If
WorkBk.Sheets(1).Range("A" & lngLastRow).Value = WorkBk.Name
NextWkb:
'Close file and save changes
WorkBk.Close True
'Next file
FileName = Dir()
Loop
If ErrNumbers <> 0 Then
MsgBox "There were some problems with Excel files. Check if there is some empty sheet or empty A column in one or more Excel files and try again"
Else
MsgBox "Everything went fine!"
End If
End Sub
Function GetFolder(strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function

Related

Insert name of the file

I have a folder with many different files and I want to insert a column with the name of the file.
This is my code:
Sub AllWorkbooks()
Dim MyFolder As String 'Path collected from the folder picker dialog
Dim MyFile As String 'Filename obtained by DIR function
Dim wbk As Workbook 'Used to loop through each workbook
On Error Resume Next
Application.ScreenUpdating = False
'Opens the folder picker dialog to allow user selection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
MyFile = Dir(MyFolder) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
Do While MyFile <> ""
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(Filename:=MyFolder & MyFile)
'Replace the line below with the statements you would want your macro to perform
Sheets(1).Range("j1").Value = "Date"
wbk.Close savechanges:=True
MyFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = True
End Sub
So what I want to do is add some part of the file name to the entire J column except the header that is "Date" which I already implemented in the code above.
Thanks in advance
Add this code just after your "Date" value setting and before you close and save changes:
Dim i As Long
For i = 2 To Sheets(1).UsedRange.Rows.Count
Sheets(1).Range("J" & i).Value = MyFile
Next i
This will insert the whole filename to the J column for each row, except for the header (2), that has data in the sheet. You should now be able to adapt this code for "some part of the filename" (you don't say which part!).

VBA saveas newly created Excel sheet using old Word Document's title

I can create a new workbook by using the method
workbooks.add
However, I need to save it with the same file name as the previous Word document which I manually copied all the useful data into it.
I have done some research into this and have found out about this method in VBA called
saveas
but whenever I try, it fails to save the new file with the same name as the Word document.
This was my code...
Dim wdFileName As Variant
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Workbooks.Add
MyPath = "D:\Analysis\"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
'this line below selects the word file to be chosen
MyFile = Dir(MyPath & "*.docx", vbNormal)
'If no files were found, exit the sub
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
'Loop through each word file in the folder
Do While Len(MyFile) > 0
'Assign the date/time of the current file to a variable
LMD = FileDateTime(MyPath & MyFile)
'If the date/time of the current file is greater than the latest
'recorded date, assign its filename and date/time to variables
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
'Get the next word file from the folder
MyFile = Dir
Loop
wdFileName = MyPath & LatestFile
(extra code here)
(extra code here)
ActiveWorkbook.SaveAs Filename:=wdFileName, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
(the last 2 lines of code do not seem to have any effect at all and it does not save the Excel with the same title name as the Word document I get my data from)
As I'm still new in VBA, help would be much appreciated with thanks!
Please do provide clear code to aid in my learning.

Import all type of files (cvs, xls, txt) to one master excel file from a folder directory

I'm working on a macro that needs to select any folder I want and import every type of file within that folder that's cvs, xls, txt and put them all into 1 workbook (not sheet). So all the tabs imported would be there. Right now the code can take in only 1 type. I tried changing the code below to:
fileName = Dir(directory & "*.csv, *.xls,*.txt")
but nothing happened.
The macro below has a fixed directory path right now but I would like to have a dialog box pop up which allows me to be flexible in selecting any folder I want to import my files from. Here's what I got so far, but please modify it or make a new one that best works.
Sub Input_Sheets()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim WrdArray() As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
directory = "C:\Users\ktam\Desktop\New folder\"
'Switch to the preferred type the folders hold. (It cannot hold 2 types)
'fileName = Dir(directory & "*.xl??")
fileName = Dir(directory & "*.csv")
'As long as the file name is found in the folder, import the file.
Do While fileName <> ""
Workbooks.Open (directory & fileName) 'Opens a random file from the folder
'WrdArray() = Split(fileName, ".")
For Each sheet In Workbooks(fileName).Worksheets
'Workbooks(fileName).ActiveSheet.Name = WrdArray(0) '0 Puts in the name of the document
total = ThisWorkbook.Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy After:=ThisWorkbook.Worksheets(total)
Next sheet
Workbooks(fileName).Close
fileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "Complete"
End Sub
I have this code that's really useful for looping within a folder and loading the files into an array based on the file names:
Global sfolder As String
sub file_merger()
file = Dir(folderchooser)
dim trackerfiles(1 to 500) as variant
counter = 1
Do While file <> ""
if instr(1,file,".xlsx") > 0 or instr(1,file,".csv") > 0 then
trackerfiles(counter) = sfolder & "\" & file
file = Dir()
counter = counter + 1
If file = "" Then
Exit Do
End If
End if
Loop
end sub
Function folderchooser() As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a folder"
.AllowMultiSelect = False
.Show
sfolder = .SelectedItems(1)
End With
folderchooser = sfolder & "\"
End Function
You could use it load into an array and then write your own code to import the files into your workbook (the tricky part is looping through the folder).

get a specific column data with column name "CC" from different excel sheets from different folders

I have 5 folders namely:
version1
version2
version3
version4
version5
each of this folders have four excel files:
gt
ga
ra
fe
ca
I want to fetch a specific column data with column name CC from each of this excel files into different sheets in a workbook. Data is to be fetched from all the folders into single file using VBA. Any assistance please? Thanks!
This code should do what you are looking for.
Note that this code will look in the first row of every workbook to find the value "CC". Also note that this assumes data is on the first sheet of every workbook.
Sub CopyColumns()
Dim TargetWb, SourceWb As Workbook
Dim myPath, myFile, myExtension, LastRowSource, LastRowTarget As String
Dim SourceColNo, TargetColNo, RowNo, SheetNo As Long
Dim Folder, FolderArray As Variant
Dim CopyHeaders As Boolean
Set TargetWb = ActiveWorkbook
Application.ScreenUpdating = False
'******************************************************************************************
' ************************* USER VARIABLES - PLEASE CHANGE ********************************
'******************************************************************************************
'Set Column Index to which data will be entered on this workbook
TargetColNo = 1
'Set the sheet number you wish to start inserting data from
SheetNo = 1
'Copy header row
CopyHeader = True
'Set Target Folder Path which contains folders "Version1" etc
myPath = "C:\New\"
'Target File Extension (must include wildcard "*")
myExtension = "*.xlsx"
'Folder names to search, should you wish to change, add or remove any
FolderArray = Array("version1", "version2", "version3", "version4", "version5")
'******************************************************************************************
'******************************************************************************************
'******************************************************************************************
'Convert Col No to Letter
Dim TgtColLetter
TgtColLetter = Split(Cells(1, TargetColNo).Address(True, False), "$")
'Loop through folders
For Each Folder In FolderArray
'Target Path with Ending Extention
myFile = Dir(myPath & Folder & "\" & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set SourceWb = Workbooks.Open(Filename:=myPath & Folder & "\" & myFile)
'Find Column named 'CC'
SourceColNo = WorksheetFunction.Match("CC", SourceWb.Sheets(1).Range("A1:H1"), 0)
Dim SrcColLetter
SrcColLetter = Split(Cells(1, SourceColNo).Address(True, False), "$")
'Get Last Row of Source Workbook
LastRowSource = SourceWb.Sheets(1).Cells(Rows.Count, SourceColNo).End(xlUp).Row
'Get Last Row of Target Workbook and add new sheets as required
On Error Resume Next
LastRowTarget = TargetWb.Sheets(SheetNo).Cells(Rows.Count, TargetColNo).End(xlUp).Row
If Err.Number <> 0 Then
TargetWb.Activate
TargetWb.Sheets.Add After:=TargetWb.Worksheets(Worksheets.Count)
End If
On Error GoTo 0
If CopyHeader = False Then
RowNo = 2
Else
RowNo = 1
End If
'Copy from Source to Target
SourceWb.Sheets(1).Range(SrcColLetter(0) & RowNo & ":" & SrcColLetter(0) & LastRowSource).Copy _
Destination:=TargetWb.Sheets(SheetNo).Range(TgtColLetter(0) & LastRowTarget)
'Close Workbook
SourceWb.Close SaveChanges:=False
'Get next file name
myFile = Dir
'Move to next sheet on TargetWb
SheetNo = SheetNo + 1
Loop
Next Folder
Application.ScreenUpdating = True
End Sub

VBA To find strings in Column A inside a specific folder contains several types of files

i need a code to meet the below requirements
Column A of an excel sheet contains some strings
i will specify a folder to search those strings
in that specified folder, there will be sub folders, and several types of files eg : .txt, .c, .xml etc..
4.i need search the strings one by one in entire folder structure and log all the result like
search strings in column A Howmany occurance in File(s) in B file locations in C
thank you
the below code will search file names entered in column A and stores the location in B
i tried the below:
Option Explicit
Dim fso As New FileSystemObject
Dim i As Long
Dim fld As Folder
Dim c As Range
Sub Find_Path()
Dim nDirs As Long, nFiles As Long, lSize As Currency
Dim sDir As String, sSrchString As String, sItem As String
Dim fldr As FileDialog
111:
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = "D:\Check\" 'ActiveWorkbook.Path & "\"
.Show
If .SelectedItems.Count = 0 Then
MsgBox "Folder to search is not selected"
GoTo 111
Else
sDir = .SelectedItems(1)
End If
End With
MsgBox "You have selected : " & sDir, vbInformation
'Application.Cursor = xlWait
Application.DisplayStatusBar = True
Application.StatusBar = "Please wait..."
For Each c In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)
sSrchString = Range("A" & c.Row).Value
lSize = FindFile(sDir, sSrchString, nDirs, nFiles)
If Str(nFiles) = 0 Then
Range("B" & c.Row).Value = "Not Found in the Folder : " & sDir
End If
Next
Application.Cursor = xlDefault
Application.StatusBar = False
End Sub
This will search for files in folder and sub folders. but i need to search string
This is how you can go through a file... Just add it for every file you want to search in
Dim filenum, targetfile, Line
filenum = FreeFile
targetfile = "C:\Mytextfile.txt"
Open targetfile For Input As filenum
Do While Not EOF(filenum)
Input #filenum, Line
'if InStr(1, Line, yourSearchString) then 'check if your string is in this line
Loop
Close filenum