I have several excel files in folder & want to rename only specific sheets of every file in the folder which contains
viz. GTLB, SALARY, GROC
Every file has a single sheet of above characters, other sheets have different names.
So, if sheet name contains above characters then change it to GROCERY.
thanks in advance
Try using this it will loop through the folder try finding files (excel files) and try looking for the strings in files that have been specified and if match found change the name.
Sub LoopThroughFiles()
'loops through all files in a folder
Dim MyObj As Object, MySource As Object, file As Variant
Dim wbk As Workbook
Dim path As String
Dim st As String
file = Dir("H:\TestCopy\testing\") 'file name
path = "H:\TestCopy\testing\" 'directory path
While (file <> "")
Set wbk = Workbooks.Open("H:\TestCopy\testing\" & file)
MsgBox "found " & file
' path = path & file 'path and filename
Call newloopTrhoughBooks
wbk.Save
wbk.Close
' Call loop_through_all_worksheets(path)
file = Dir
Wend
End Sub
Sub newloopTrhoughBooks()
Dim book As Workbook, sheet As Worksheet, text As String, text1 As String
Dim logic_string As String
Dim logic_string2 As String
Dim logic_string3 As String
logic_string = "GTLB"
logic_string2 = "SALARY"
logic_string3 = "GROC"
For Each book In Workbooks
text = text & "Workbook: " & book.Name & vbNewLine & "Worksheets: " & vbNewLine
For Each sheet In book.Worksheets
text = text & sheet.Name & vbNewLine
text1 = sheet.Name
If StrComp(logic_string, text1) = 1 Or StrComp(logic_string2, text1) = 1 Or StrComp(logic_string3, text1) = 1 Then 'compare file name
ActiveSheet.Name = text1
ActiveSheet.Name = "Change1"
End If
Next sheet
text = text & vbNewLine
Next book
MsgBox text
End Sub
Sub RenameSheets()
Dim MyFolder As String
Dim MyFile As String
Dim wbname As String
MyFolder = "E:\SSS\File Name"
MyFile = Dir(MyFolder & "\*.xls")
Application.ScreenUpdating = False
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
With ActiveWorkbook
wbname = "GROCERY"
'For giving filename to sheet1
'Left(.Name, InStr(.Name, ".") - 1)
For Each sheet In ActiveWorkbook.Sheets
If LCase(sheet.Name) Like "*salary*" Or LCase(sheet.Name) Like "*gtlb*" Or LCase(sheet.Name) Like "*groc*" Then
MsgBox "Found! " & sheet.Name
.Sheets(sheet.Name).Name = wbname
.Close savechanges:=True
End If
Next
'.Sheets(1).Name = wbname
'.Close savechanges:=True
End With
MyFile = Dir
Loop
Application.ScreenUpdating = True
End Sub
Related
I want to run through a specific sheet (from & to) save those ws as a new file in a folder, if the folder doesn't exist then create.
I'm able to do it to one sheet.
ActiveSheet.Next.Select
If Range("F3").Value = "" Then
Windows("Import OT.xlsm").Activate
Sheets("Cash").Select
Dim filename101 As String
Dim path101 As String
Application.DisplayAlerts = False
path101 = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
filename101 = Range("B1").Value & ".xlsx"
ActiveWorkbook.SaveAs path101 & Range("A2") & "\" & Range("A1") & " " & filename101,xlOpenXMLWorkbook
Application.DisplayAlerts = True
Else
Cells.Select
Range("F3").Activate
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Dim Path1 As String
Dim fpathname1 As String
Path1 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\"
fpathname1 = Path1 & Range("F3") & "\" & Range("F2") & " " & Range("B3") & ".xlsx"
path01 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & Range("F3")
Dim path001 As String
Dim Folder As String
Folder = Dir(path01, vbDirectory)
If Folder = vbNullString Then
VBA.FileSystem.MkDir (path01)
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
Else
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
End If
End If
End Sub
I want this as a loop is because I have a few tens of sheets. For it to work I think I need to write it specific time, but with loop I learned I don't need to do that.
Excel file sheet
https://onedrive.live.com/view.aspx?resid=AF6FF2618C09AC74!29027&ithint=file%2cxlsx&authkey=!AHcJjYCu8D0NTNY
According to your comment where you wrote the steps:
Read the comments
Try to run the code using F8 key and see where you need to change it.
As you're learning, please note to first write the steps in plain English Norsk and then develop your code.
See how I just followed your steps with readable code.
Code:
Public Sub GenerateCustomersFiles()
' 1) Active sheet (oppgjør 1-20)
Dim targetSheet As Worksheet
For Each targetSheet In ThisWorkbook.Sheets
' Check only sheets with string in name
If InStr(targetSheet.Name, "Oppgjør") > 0 Then
' 2) look if value in F3 is empty
If targetSheet.Range("F3").Value = vbNullString Then
' 3) if it is, do select "cash" sheet and save this file (its name and path are given above what it should be named)
Dim fileName As String
Dim filePath As String
Dim folderPath As String
folderPath = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
fileName = targetSheet.Range("B1").Value & ".xlsx"
filePath = folderPath & targetSheet.Range("A2") & "\" & targetSheet.Range("A1") & " " & fileName
ThisWorkbook.Worksheets("Cash").Select
ThisWorkbook.SaveAs filePath, xlOpenXMLWorkbook
Else
' 4) if it doesn't, do open selected sheet to a new workbook and save that in clients name folder (folder and path given above in code section)
folderPath = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & targetSheet.Range("F3")
fileName = targetSheet.Range("F2") & " " & targetSheet.Range("B3") & ".xlsx"
filePath = folderPath & "\" & fileName
' 5) check if clients folder exist or not for the file to be saved in.
' if folder doesnt exist,
' create new and save file there.
CreateFoldersInPath folderPath
' if folder exist just save the file there
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Add
targetSheet.Copy before:=targetWorkbook.Sheets(1)
targetWorkbook.SaveAs filePath, 51
targetWorkbook.Close
End If
End If
Next targetSheet
End Sub
' Credits: https://stackoverflow.com/a/31034201/1521579
Private Sub CreateFoldersInPath(ByVal targetFolderPath As String)
Dim strBuildPath As String
Dim varFolder As Variant
If Right(targetFolderPath, 1) = "\" Then targetFolderPath = Left(targetFolderPath, Len(targetFolderPath) - 1)
For Each varFolder In Split(targetFolderPath, "\")
If Len(strBuildPath) = 0 Then
strBuildPath = varFolder & "\"
Else
strBuildPath = strBuildPath & varFolder & "\"
End If
If Len(Dir(strBuildPath, vbDirectory)) = 0 Then MkDir strBuildPath
Next varFolder
'The full folder path has been created regardless of nested subdirectories
'Continue with your code here
End Sub
Let me know how it goes
I want to open workbooks from particular folder, starting with Specific string listed down in Excel sheet.
Example :
I have an excel list -
123456
567890
654321
And the file names are starting with these numbers are like :
123456_example_stringxxxx.xlsx
567890 example stringxx.xlsx
654321-example stringxxxx.xlsx
stored at : C:\Users\Desktop\Testr\Excel_Files
Below is my code, but it opens just first file, I am trying to add loop but giving errors.
Sub Macro1()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim listFileName As String
Dim listName As String
Dim rowCount As Integer
rowCount = 1
listFileName = ActiveSheet.Range("A" & rowCount).Value
listName = listFileName & "*"
myPath = "C:\Users\Desktop\Test\Excel_Files"
myFile = Dir(myPath & listName & ".xlsx", vbNormal)
If Len(myFile) = 0 Then
'(Here I Want to add such kind of part's list to a text file)
Else
Workbooks.Open myPath & myFile
MsgBox "Successfull", vbInformation, "Opened Sucessfully"
End If
End Sub
Please sugest how can I create a loop or any better & simple code for it.
In addition ,
I want to search names from A1 to A10
Msg elert "Sucessfull" shouldnt be looped, it should be displayed at the end of process.
When any file is not found , the process shouldnt be stopped, it will list down the objects which are not found into a text file.
Regards,
Vivek Chotaliya
First you need to determine the last row used in column A, we do this using this line of code rowCount = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row, once that's done you can use a For Next loop to open all files that match column A listName.
inside the For Next I validate if the file was found, if it wasn't then it will call a small function to create a .txt file.
Give it a try to this...
Option Explicit
Public Sub Open_Workbooks()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim listFileName As String
Dim rowCount As Long
Dim i As Long
Dim bool As Boolean
bool = False
rowCount = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To rowCount
listFileName = ActiveSheet.Cells(i, 1)
myPath = "C:\Users\" & Environ("Username") & "\Desktop\Test\Excel_Files\"
myExtension = "*.xlsx"
myFile = Dir(myPath & listFileName & myExtension)
If Not Len(myFile) = 0 Then
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'do somenthing
'
'
'
'
'
'
'
wb.Close SaveChanges:=False
Else
Call Create_txt_Log(listFileName)
bool = True
End If
Next
If bool = False Then
MsgBox "Successfull", vbInformation, "Opened Sucessfully"
Else
MsgBox "Successfull but not all files where opened check text log file", vbInformation, "Opened Sucessfully"
End If
End Sub
Function...
Public Function Create_txt_Log(ByVal listFileName As String)
Dim Fileout As Object
Dim FSO As Object
Dim FolderPath As String
Dim myNotePadName As String
Dim myPath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
myNotePadName = "Not_Found.txt"
myPath = "C:\Users\" & Environ("Username") & "\Desktop\Test\Files_Not_Found\"
FolderPath = myPath & myNotePadName
If FSO.FileExists(FolderPath) = False Then
Set Fileout = FSO.CreateTextFile(myPath & myNotePadName)
Fileout.Write listFileName
Fileout.Close
Else
Set Fileout = FSO.OpenTextFile(FolderPath, 8)
Fileout.Write vbCrLf & listFileName
Fileout.Close
End If
End Function
The code imports all the worksheets on all the Excel files on my folder.
I added a command button as suggested in the website where I got this code. In the long run I would like to apply the data imported to a table I have on the main worksheet, followed by printing the template and then deleting the information so I can start over with the next recent spreadsheet.
For now I only want to know how to import the most recent file to my worksheet.
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
directory = "C:\ExcelPract\"
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
Workbooks.Open (directory & fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("Docket .xls").Worksheets.count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("Docket .xls").Worksheets(total)
Next sheet
Workbooks(fileName).Close
fileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
You could use the below code and call the NewestFile function from the CommandButton1_Click(). I have only replaced the below line in your Sub.
fileName = NewestFile(directory, "*.xls")
Function NewestFile(directory, FileSpec)
' Returns the name of the most recent file in a Directory
' That matches the FileSpec (e.g., "*.xls").
' Returns an empty string if the directory does not exist or
' it contains no matching files
Dim fileName As String
Dim MostRecentFile As String
Dim MostRecentDate As Date
If Right(directory, 1) <> "\" Then directory = directory & "\"
fileName = Dir(directory & FileSpec, 0)
If fileName <> "" Then
MostRecentFile = fileName
MostRecentDate = FileDateTime(directory & fileName)
Do While fileName <> ""
If FileDateTime(directory & fileName) > MostRecentDate Then
MostRecentFile = fileName
MostRecentDate = FileDateTime(directory & fileName)
End If
fileName = Dir
Loop
End If
NewestFile = MostRecentFile
End Function
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
directory = "C:\ExcelPract\"
fileName = NewestFile(directory, "*.xls")
Do While fileName <> ""
Workbooks.Open (directory & fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("Docket .xls").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("Docket .xls").Worksheets(total)
Next sheet
Workbooks(fileName).Close
fileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Seeking support to edit below codes in such a way that it renames all worksheets (excel) similar to their workbooknames within a folder (loop). If workbook has more than one sheet then rename it as workbookname(1),workbookname(2) etc.
Sub EditSheetName()
Dim NewName
NewName = Replace(ActiveWorkbook. Name, ".xl*", "")
ActiveSheet.Select
ActiveSheet.Name = NewName
End Sub
Maybe just a simple loop:
I haven't figured out how to replace the ".xlsx" using a wildcard, I would assume it would be either ".xlsm" or ".xlsx", you can change them in the code
Sub LoopThroughFolder()
Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
Dim sh As Worksheet
Dim s As String, n As String
Set Wb = ThisWorkbook
'change the address to suite
MyDir = "C:\Users\dmorrison\Downloads\TestFolderLoop\"
MyFile = Dir(MyDir & "*.xls*") 'change file extension
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While MyFile <> ""
Workbooks.Open (MyFile)
s = ActiveWorkbook.Name
n = Replace(s, ".xls", "") 'change the file extension
i = 1
For Each sh In Sheets
sh.Name = n & "(" & i & ")"
i = i + 1
Next sh
ActiveWorkbook.Close True
MyFile = Dir()
Loop
End Sub
For multiple sheets, you will want an if statement:
Dim s As String, i as Integer
If Sheets.Count=1 Then
s = Replace(ActiveWorkbook.Name,".xlsx","")
ActiveSheet.Name = s
Else
For i = 1 to Sheets.Count
s = Replace(ActiveWorkbook.Name,".xlsx","")
Sheets(i).Name = s & "(" & i & ")"
Next i
End If
I have it this way so the (#) only shows up for multiple. You would only need the loop in the Else section if you don't care.
How to copy the entire worksheet from a workbook and save it as new workbook to a specific directory with the customized filename(I am trying to pick the filename from on of the cells in the worksheet. The sheet that I need to copy has few merged cells too.
Sub CopyItOver()
Dim fname As String
Dim fpath As String
Dim NewBook As Workbook
Dim name as String
fpath = "C:\Users\..\"
fname = "List" & name & ".xlsm"
name = Range("c3").Value
Set NewBook = Workbooks.Add
ActiveWorkbook.Sheets("Generator").Copy Before:=NewBook.Sheets(1)
If Dir(fpath & "\" & fname) <> "" Then
MsgBox "File " & fpath & "\" & fname & " already exists"
Else
NewBook.SaveAs FileName:=fpath & "\" & fname
End If
End Sub
When I run this it, give me Subscript out of range error in this line
ActiveWorkbook.Sheets("Generator").Copy Before:=NewBook.Sheets(1)
Suggest you try it like this:
Check to see if Generator exists before progressing
If you use .Copy then the worksheet is automatically copied to a new workbook (so you don't need to add a new book first)
code
Sub CopyItOver()
Dim fname As String
Dim fpath As String
Dim name As String
Dim ws As Worksheet
fpath = "C:\Users\..\"
fname = "List" & name & ".xlsm"
name = Range("c3").Value
On Error Resume Next
Set ws = ThisWorkbook.Sheets("Generator")
On Error GoTo 0
If ws Is Nothing Then
MsgBox "sheet doesn't exist"
Exit Sub
End If
If Dir(fpath & "\" & fname) = vbNullString Then
ThisWorkbook.Sheets("Generator").Copy
ActiveWorkbook.SaveAs Filename:=fpath & "\" & fname
Else
MsgBox "File " & fpath & "\" & fname & " already exists"
End If
End Sub