Loop through directory open every file activate sheet and add new column










0














I have made code that needs to do the following:



  1. scan directory op.xlsx file #please review

  2. open file activate sheet "Buitendelen" (some files don't have so skip file and go on)

  3. if sheet "buitendelen" is activated add new column between C and D

  4. save file

  5. close file

  6. go on to next file

It sometimes does not work or it crashes after some time editing files.



Sub AllFiles_click()
'//Change the path to the main folder, accordingly
Call RecursiveFolders("C:testlabtestmap")
End Sub

Sub RecursiveFolders(ByVal MyPath As String)

Dim FileSys As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim wkbOpen As Workbook

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set objFolder = FileSys.GetFolder(MyPath)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

'open every folder and subfolder
For Each objSubFolder In objFolder.SubFolders

'search for file in folder and subfolder
For Each objFile In objSubFolder.Files

'set open workbook
Set wkbOpen = Workbooks.Open(filename:=objFile)

'call passwordfirst code to unlock sheets
Call passwordfirst

'activated sheet buitendelen
wkbOpen.Sheets("Buitendelen").Activate

'call columnadd code to add column
Call columnadd

'close workbook and save
wkbOpen.Close savechanges:=True
Next

'start over again
Call RecursiveFolders(objSubFolder.Path)

Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

'code to unlock sheets with password
Sub passwordfirst()
ActiveSheet.Unprotect Password:="Freonr410a"
End Sub

'code to add column
Private Sub columnadd()
Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub









share|improve this question



















  • 1




    Just an FYI, you should really take your password out of this.
    – Josh Eller
    Jul 23 '18 at 16:35










  • when it crashes what error do you get? also check the comment on step 1
    – Yuca
    Jul 23 '18 at 17:03










  • Just another FYI `Columns("D:D").Insert' will not insert a column between D and E
    – GMalc
    Jul 23 '18 at 17:34










  • @yuca path is right and erro is fout 1004 method insert classe range failed on [code]Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove[/code]@josh eller password is fake
    – eVinx
    Jul 23 '18 at 17:47










  • @eVinx a directory can't have a file extension. It is unclear what you mean in your step 1
    – Yuca
    Jul 23 '18 at 17:49















0














I have made code that needs to do the following:



  1. scan directory op.xlsx file #please review

  2. open file activate sheet "Buitendelen" (some files don't have so skip file and go on)

  3. if sheet "buitendelen" is activated add new column between C and D

  4. save file

  5. close file

  6. go on to next file

It sometimes does not work or it crashes after some time editing files.



Sub AllFiles_click()
'//Change the path to the main folder, accordingly
Call RecursiveFolders("C:testlabtestmap")
End Sub

Sub RecursiveFolders(ByVal MyPath As String)

Dim FileSys As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim wkbOpen As Workbook

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set objFolder = FileSys.GetFolder(MyPath)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

'open every folder and subfolder
For Each objSubFolder In objFolder.SubFolders

'search for file in folder and subfolder
For Each objFile In objSubFolder.Files

'set open workbook
Set wkbOpen = Workbooks.Open(filename:=objFile)

'call passwordfirst code to unlock sheets
Call passwordfirst

'activated sheet buitendelen
wkbOpen.Sheets("Buitendelen").Activate

'call columnadd code to add column
Call columnadd

'close workbook and save
wkbOpen.Close savechanges:=True
Next

'start over again
Call RecursiveFolders(objSubFolder.Path)

Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

'code to unlock sheets with password
Sub passwordfirst()
ActiveSheet.Unprotect Password:="Freonr410a"
End Sub

'code to add column
Private Sub columnadd()
Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub









share|improve this question



















  • 1




    Just an FYI, you should really take your password out of this.
    – Josh Eller
    Jul 23 '18 at 16:35










  • when it crashes what error do you get? also check the comment on step 1
    – Yuca
    Jul 23 '18 at 17:03










  • Just another FYI `Columns("D:D").Insert' will not insert a column between D and E
    – GMalc
    Jul 23 '18 at 17:34










  • @yuca path is right and erro is fout 1004 method insert classe range failed on [code]Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove[/code]@josh eller password is fake
    – eVinx
    Jul 23 '18 at 17:47










  • @eVinx a directory can't have a file extension. It is unclear what you mean in your step 1
    – Yuca
    Jul 23 '18 at 17:49













0












0








0







I have made code that needs to do the following:



  1. scan directory op.xlsx file #please review

  2. open file activate sheet "Buitendelen" (some files don't have so skip file and go on)

  3. if sheet "buitendelen" is activated add new column between C and D

  4. save file

  5. close file

  6. go on to next file

It sometimes does not work or it crashes after some time editing files.



Sub AllFiles_click()
'//Change the path to the main folder, accordingly
Call RecursiveFolders("C:testlabtestmap")
End Sub

Sub RecursiveFolders(ByVal MyPath As String)

Dim FileSys As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim wkbOpen As Workbook

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set objFolder = FileSys.GetFolder(MyPath)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

'open every folder and subfolder
For Each objSubFolder In objFolder.SubFolders

'search for file in folder and subfolder
For Each objFile In objSubFolder.Files

'set open workbook
Set wkbOpen = Workbooks.Open(filename:=objFile)

'call passwordfirst code to unlock sheets
Call passwordfirst

'activated sheet buitendelen
wkbOpen.Sheets("Buitendelen").Activate

'call columnadd code to add column
Call columnadd

'close workbook and save
wkbOpen.Close savechanges:=True
Next

'start over again
Call RecursiveFolders(objSubFolder.Path)

Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

'code to unlock sheets with password
Sub passwordfirst()
ActiveSheet.Unprotect Password:="Freonr410a"
End Sub

'code to add column
Private Sub columnadd()
Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub









share|improve this question















I have made code that needs to do the following:



  1. scan directory op.xlsx file #please review

  2. open file activate sheet "Buitendelen" (some files don't have so skip file and go on)

  3. if sheet "buitendelen" is activated add new column between C and D

  4. save file

  5. close file

  6. go on to next file

It sometimes does not work or it crashes after some time editing files.



Sub AllFiles_click()
'//Change the path to the main folder, accordingly
Call RecursiveFolders("C:testlabtestmap")
End Sub

Sub RecursiveFolders(ByVal MyPath As String)

Dim FileSys As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim wkbOpen As Workbook

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set objFolder = FileSys.GetFolder(MyPath)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

'open every folder and subfolder
For Each objSubFolder In objFolder.SubFolders

'search for file in folder and subfolder
For Each objFile In objSubFolder.Files

'set open workbook
Set wkbOpen = Workbooks.Open(filename:=objFile)

'call passwordfirst code to unlock sheets
Call passwordfirst

'activated sheet buitendelen
wkbOpen.Sheets("Buitendelen").Activate

'call columnadd code to add column
Call columnadd

'close workbook and save
wkbOpen.Close savechanges:=True
Next

'start over again
Call RecursiveFolders(objSubFolder.Path)

Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

'code to unlock sheets with password
Sub passwordfirst()
ActiveSheet.Unprotect Password:="Freonr410a"
End Sub

'code to add column
Private Sub columnadd()
Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub






excel vba






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 12 '18 at 1:33









Community

11




11










asked Jul 23 '18 at 16:12









eVinxeVinx

16




16







  • 1




    Just an FYI, you should really take your password out of this.
    – Josh Eller
    Jul 23 '18 at 16:35










  • when it crashes what error do you get? also check the comment on step 1
    – Yuca
    Jul 23 '18 at 17:03










  • Just another FYI `Columns("D:D").Insert' will not insert a column between D and E
    – GMalc
    Jul 23 '18 at 17:34










  • @yuca path is right and erro is fout 1004 method insert classe range failed on [code]Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove[/code]@josh eller password is fake
    – eVinx
    Jul 23 '18 at 17:47










  • @eVinx a directory can't have a file extension. It is unclear what you mean in your step 1
    – Yuca
    Jul 23 '18 at 17:49












  • 1




    Just an FYI, you should really take your password out of this.
    – Josh Eller
    Jul 23 '18 at 16:35










  • when it crashes what error do you get? also check the comment on step 1
    – Yuca
    Jul 23 '18 at 17:03










  • Just another FYI `Columns("D:D").Insert' will not insert a column between D and E
    – GMalc
    Jul 23 '18 at 17:34










  • @yuca path is right and erro is fout 1004 method insert classe range failed on [code]Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove[/code]@josh eller password is fake
    – eVinx
    Jul 23 '18 at 17:47










  • @eVinx a directory can't have a file extension. It is unclear what you mean in your step 1
    – Yuca
    Jul 23 '18 at 17:49







1




1




Just an FYI, you should really take your password out of this.
– Josh Eller
Jul 23 '18 at 16:35




Just an FYI, you should really take your password out of this.
– Josh Eller
Jul 23 '18 at 16:35












when it crashes what error do you get? also check the comment on step 1
– Yuca
Jul 23 '18 at 17:03




when it crashes what error do you get? also check the comment on step 1
– Yuca
Jul 23 '18 at 17:03












Just another FYI `Columns("D:D").Insert' will not insert a column between D and E
– GMalc
Jul 23 '18 at 17:34




Just another FYI `Columns("D:D").Insert' will not insert a column between D and E
– GMalc
Jul 23 '18 at 17:34












@yuca path is right and erro is fout 1004 method insert classe range failed on [code]Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove[/code]@josh eller password is fake
– eVinx
Jul 23 '18 at 17:47




@yuca path is right and erro is fout 1004 method insert classe range failed on [code]Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove[/code]@josh eller password is fake
– eVinx
Jul 23 '18 at 17:47












@eVinx a directory can't have a file extension. It is unclear what you mean in your step 1
– Yuca
Jul 23 '18 at 17:49




@eVinx a directory can't have a file extension. It is unclear what you mean in your step 1
– Yuca
Jul 23 '18 at 17:49












1 Answer
1






active

oldest

votes


















0














I saw couple of things regarding your code and question. First off, line:



ActiveSheet.Unprotect Password:="Freonr410a"


This line, sometimes might cause some issues because, your first active sheet, after you open particular workbook, might not be the Buitendelen worksheet. You are depending on someone (or yourself) to close workbook with this sheet active (tricky thing).



This line:



Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove


... might also be a root of some problems if it comes to adding new columns. Image that your first worksheet isn't Buitendele worksheet. You can successful unlock unprotected worksheet, but now you are trying to add new column to completely different worksheet. Unacceptable.



I saw also that you are omitting any files (except folders) inside your root folder ("C:testlabtestmap"). That means, if you have any files inside TestMap folder, they will be left untouched. I don't know if this is desired thing or not.



Here, you can find a solution for your problem (tested on W10/ Excel 2017 32 bit)



Sub AllFiles_click()
Call RecursiveFolders("C:testlabtestmap")
End Sub

' Go through every folder starting from objFolder
' location recursively and add one column after column D
' inside workbook. If Buitendelen worksheet does not exists,
' go to next workbook.
Sub RecursiveFolders(ByVal MyPath As String)
Const BuitendelenWsName as String = "Buitendelen"

Dim FileSys As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim wkbOpen As Workbook
Dim wshToEdit as Worksheet

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set objFolder = FileSys.GetFolder(MyPath)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

For Each objSubFolder In objFolder.SubFolders
For Each objFile In objSubFolder.Files
Set wkbOpen = Workbooks.Open(filename:=objFile)

If SheetExists(BuitendelenWsName, wkbOpen) Then
Set wshToEdit = wkbOpen.Worksheets(BuitendelenWsName)

' Before any changes, worksheet has to be unprotected.
wshToEdit.Unprotect Password:="Freonr410a"
wshToEdit.Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End if

wkbOpen.Close savechanges:=True
Next
Call RecursiveFolders(objSubFolder.Path)
Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True

set FileSys = nothing
set objFolder = nothing
set objSubFolder = nothing
set objFile = nothing
set wkbOpen = nothing
set wshToEdit = nothing
End Sub

Public Function SheetExists(byval sheetToFind As String, byref container as Workbook) As Boolean
Dim sht as Worksheet

SheetExists = False
For Each sht In container.Worksheets
If sheetToFind = sht.name Then
SheetExists = True
Exit For
End If
Next sht

set sht = nothing
End Function


Extra notes: Please, work on your naming conventions, AllFiles or RecursiveFolders tells nothing about the body of subroutines.



Variable naming conventions: Be precise, if you are going to use Hungarian notation use it - FileSys should be changed to objFileSys.






share|improve this answer






















  • thanks for you cleaner code the only thing there are also files that has not the sheet "Buitendelen" but only the sheet "Bezoekers registratie" is there a option to skip this file and go on to next on i think something like if workbook contains 1sheet skip if 2 do the thing
    – eVinx
    Jul 24 '18 at 17:19










  • There is not built in function which will allow to check if worksheet exists or not. I've updated my answer. If you find my reply useful, please mark my answer as "Answer". Also +1 is much appreciated :)
    – FlameHorizon
    Jul 25 '18 at 7:19










  • thanks in advance this works great :)
    – eVinx
    Jul 25 '18 at 15:59










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51483174%2floop-through-directory-open-every-file-activate-sheet-and-add-new-column%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














I saw couple of things regarding your code and question. First off, line:



ActiveSheet.Unprotect Password:="Freonr410a"


This line, sometimes might cause some issues because, your first active sheet, after you open particular workbook, might not be the Buitendelen worksheet. You are depending on someone (or yourself) to close workbook with this sheet active (tricky thing).



This line:



Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove


... might also be a root of some problems if it comes to adding new columns. Image that your first worksheet isn't Buitendele worksheet. You can successful unlock unprotected worksheet, but now you are trying to add new column to completely different worksheet. Unacceptable.



I saw also that you are omitting any files (except folders) inside your root folder ("C:testlabtestmap"). That means, if you have any files inside TestMap folder, they will be left untouched. I don't know if this is desired thing or not.



Here, you can find a solution for your problem (tested on W10/ Excel 2017 32 bit)



Sub AllFiles_click()
Call RecursiveFolders("C:testlabtestmap")
End Sub

' Go through every folder starting from objFolder
' location recursively and add one column after column D
' inside workbook. If Buitendelen worksheet does not exists,
' go to next workbook.
Sub RecursiveFolders(ByVal MyPath As String)
Const BuitendelenWsName as String = "Buitendelen"

Dim FileSys As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim wkbOpen As Workbook
Dim wshToEdit as Worksheet

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set objFolder = FileSys.GetFolder(MyPath)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

For Each objSubFolder In objFolder.SubFolders
For Each objFile In objSubFolder.Files
Set wkbOpen = Workbooks.Open(filename:=objFile)

If SheetExists(BuitendelenWsName, wkbOpen) Then
Set wshToEdit = wkbOpen.Worksheets(BuitendelenWsName)

' Before any changes, worksheet has to be unprotected.
wshToEdit.Unprotect Password:="Freonr410a"
wshToEdit.Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End if

wkbOpen.Close savechanges:=True
Next
Call RecursiveFolders(objSubFolder.Path)
Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True

set FileSys = nothing
set objFolder = nothing
set objSubFolder = nothing
set objFile = nothing
set wkbOpen = nothing
set wshToEdit = nothing
End Sub

Public Function SheetExists(byval sheetToFind As String, byref container as Workbook) As Boolean
Dim sht as Worksheet

SheetExists = False
For Each sht In container.Worksheets
If sheetToFind = sht.name Then
SheetExists = True
Exit For
End If
Next sht

set sht = nothing
End Function


Extra notes: Please, work on your naming conventions, AllFiles or RecursiveFolders tells nothing about the body of subroutines.



Variable naming conventions: Be precise, if you are going to use Hungarian notation use it - FileSys should be changed to objFileSys.






share|improve this answer






















  • thanks for you cleaner code the only thing there are also files that has not the sheet "Buitendelen" but only the sheet "Bezoekers registratie" is there a option to skip this file and go on to next on i think something like if workbook contains 1sheet skip if 2 do the thing
    – eVinx
    Jul 24 '18 at 17:19










  • There is not built in function which will allow to check if worksheet exists or not. I've updated my answer. If you find my reply useful, please mark my answer as "Answer". Also +1 is much appreciated :)
    – FlameHorizon
    Jul 25 '18 at 7:19










  • thanks in advance this works great :)
    – eVinx
    Jul 25 '18 at 15:59















0














I saw couple of things regarding your code and question. First off, line:



ActiveSheet.Unprotect Password:="Freonr410a"


This line, sometimes might cause some issues because, your first active sheet, after you open particular workbook, might not be the Buitendelen worksheet. You are depending on someone (or yourself) to close workbook with this sheet active (tricky thing).



This line:



Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove


... might also be a root of some problems if it comes to adding new columns. Image that your first worksheet isn't Buitendele worksheet. You can successful unlock unprotected worksheet, but now you are trying to add new column to completely different worksheet. Unacceptable.



I saw also that you are omitting any files (except folders) inside your root folder ("C:testlabtestmap"). That means, if you have any files inside TestMap folder, they will be left untouched. I don't know if this is desired thing or not.



Here, you can find a solution for your problem (tested on W10/ Excel 2017 32 bit)



Sub AllFiles_click()
Call RecursiveFolders("C:testlabtestmap")
End Sub

' Go through every folder starting from objFolder
' location recursively and add one column after column D
' inside workbook. If Buitendelen worksheet does not exists,
' go to next workbook.
Sub RecursiveFolders(ByVal MyPath As String)
Const BuitendelenWsName as String = "Buitendelen"

Dim FileSys As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim wkbOpen As Workbook
Dim wshToEdit as Worksheet

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set objFolder = FileSys.GetFolder(MyPath)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

For Each objSubFolder In objFolder.SubFolders
For Each objFile In objSubFolder.Files
Set wkbOpen = Workbooks.Open(filename:=objFile)

If SheetExists(BuitendelenWsName, wkbOpen) Then
Set wshToEdit = wkbOpen.Worksheets(BuitendelenWsName)

' Before any changes, worksheet has to be unprotected.
wshToEdit.Unprotect Password:="Freonr410a"
wshToEdit.Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End if

wkbOpen.Close savechanges:=True
Next
Call RecursiveFolders(objSubFolder.Path)
Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True

set FileSys = nothing
set objFolder = nothing
set objSubFolder = nothing
set objFile = nothing
set wkbOpen = nothing
set wshToEdit = nothing
End Sub

Public Function SheetExists(byval sheetToFind As String, byref container as Workbook) As Boolean
Dim sht as Worksheet

SheetExists = False
For Each sht In container.Worksheets
If sheetToFind = sht.name Then
SheetExists = True
Exit For
End If
Next sht

set sht = nothing
End Function


Extra notes: Please, work on your naming conventions, AllFiles or RecursiveFolders tells nothing about the body of subroutines.



Variable naming conventions: Be precise, if you are going to use Hungarian notation use it - FileSys should be changed to objFileSys.






share|improve this answer






















  • thanks for you cleaner code the only thing there are also files that has not the sheet "Buitendelen" but only the sheet "Bezoekers registratie" is there a option to skip this file and go on to next on i think something like if workbook contains 1sheet skip if 2 do the thing
    – eVinx
    Jul 24 '18 at 17:19










  • There is not built in function which will allow to check if worksheet exists or not. I've updated my answer. If you find my reply useful, please mark my answer as "Answer". Also +1 is much appreciated :)
    – FlameHorizon
    Jul 25 '18 at 7:19










  • thanks in advance this works great :)
    – eVinx
    Jul 25 '18 at 15:59













0












0








0






I saw couple of things regarding your code and question. First off, line:



ActiveSheet.Unprotect Password:="Freonr410a"


This line, sometimes might cause some issues because, your first active sheet, after you open particular workbook, might not be the Buitendelen worksheet. You are depending on someone (or yourself) to close workbook with this sheet active (tricky thing).



This line:



Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove


... might also be a root of some problems if it comes to adding new columns. Image that your first worksheet isn't Buitendele worksheet. You can successful unlock unprotected worksheet, but now you are trying to add new column to completely different worksheet. Unacceptable.



I saw also that you are omitting any files (except folders) inside your root folder ("C:testlabtestmap"). That means, if you have any files inside TestMap folder, they will be left untouched. I don't know if this is desired thing or not.



Here, you can find a solution for your problem (tested on W10/ Excel 2017 32 bit)



Sub AllFiles_click()
Call RecursiveFolders("C:testlabtestmap")
End Sub

' Go through every folder starting from objFolder
' location recursively and add one column after column D
' inside workbook. If Buitendelen worksheet does not exists,
' go to next workbook.
Sub RecursiveFolders(ByVal MyPath As String)
Const BuitendelenWsName as String = "Buitendelen"

Dim FileSys As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim wkbOpen As Workbook
Dim wshToEdit as Worksheet

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set objFolder = FileSys.GetFolder(MyPath)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

For Each objSubFolder In objFolder.SubFolders
For Each objFile In objSubFolder.Files
Set wkbOpen = Workbooks.Open(filename:=objFile)

If SheetExists(BuitendelenWsName, wkbOpen) Then
Set wshToEdit = wkbOpen.Worksheets(BuitendelenWsName)

' Before any changes, worksheet has to be unprotected.
wshToEdit.Unprotect Password:="Freonr410a"
wshToEdit.Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End if

wkbOpen.Close savechanges:=True
Next
Call RecursiveFolders(objSubFolder.Path)
Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True

set FileSys = nothing
set objFolder = nothing
set objSubFolder = nothing
set objFile = nothing
set wkbOpen = nothing
set wshToEdit = nothing
End Sub

Public Function SheetExists(byval sheetToFind As String, byref container as Workbook) As Boolean
Dim sht as Worksheet

SheetExists = False
For Each sht In container.Worksheets
If sheetToFind = sht.name Then
SheetExists = True
Exit For
End If
Next sht

set sht = nothing
End Function


Extra notes: Please, work on your naming conventions, AllFiles or RecursiveFolders tells nothing about the body of subroutines.



Variable naming conventions: Be precise, if you are going to use Hungarian notation use it - FileSys should be changed to objFileSys.






share|improve this answer














I saw couple of things regarding your code and question. First off, line:



ActiveSheet.Unprotect Password:="Freonr410a"


This line, sometimes might cause some issues because, your first active sheet, after you open particular workbook, might not be the Buitendelen worksheet. You are depending on someone (or yourself) to close workbook with this sheet active (tricky thing).



This line:



Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove


... might also be a root of some problems if it comes to adding new columns. Image that your first worksheet isn't Buitendele worksheet. You can successful unlock unprotected worksheet, but now you are trying to add new column to completely different worksheet. Unacceptable.



I saw also that you are omitting any files (except folders) inside your root folder ("C:testlabtestmap"). That means, if you have any files inside TestMap folder, they will be left untouched. I don't know if this is desired thing or not.



Here, you can find a solution for your problem (tested on W10/ Excel 2017 32 bit)



Sub AllFiles_click()
Call RecursiveFolders("C:testlabtestmap")
End Sub

' Go through every folder starting from objFolder
' location recursively and add one column after column D
' inside workbook. If Buitendelen worksheet does not exists,
' go to next workbook.
Sub RecursiveFolders(ByVal MyPath As String)
Const BuitendelenWsName as String = "Buitendelen"

Dim FileSys As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim objFile As Object
Dim wkbOpen As Workbook
Dim wshToEdit as Worksheet

Set FileSys = CreateObject("Scripting.FileSystemObject")
Set objFolder = FileSys.GetFolder(MyPath)

Application.ScreenUpdating = False
Application.DisplayAlerts = False

For Each objSubFolder In objFolder.SubFolders
For Each objFile In objSubFolder.Files
Set wkbOpen = Workbooks.Open(filename:=objFile)

If SheetExists(BuitendelenWsName, wkbOpen) Then
Set wshToEdit = wkbOpen.Worksheets(BuitendelenWsName)

' Before any changes, worksheet has to be unprotected.
wshToEdit.Unprotect Password:="Freonr410a"
wshToEdit.Columns("D:D").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End if

wkbOpen.Close savechanges:=True
Next
Call RecursiveFolders(objSubFolder.Path)
Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True

set FileSys = nothing
set objFolder = nothing
set objSubFolder = nothing
set objFile = nothing
set wkbOpen = nothing
set wshToEdit = nothing
End Sub

Public Function SheetExists(byval sheetToFind As String, byref container as Workbook) As Boolean
Dim sht as Worksheet

SheetExists = False
For Each sht In container.Worksheets
If sheetToFind = sht.name Then
SheetExists = True
Exit For
End If
Next sht

set sht = nothing
End Function


Extra notes: Please, work on your naming conventions, AllFiles or RecursiveFolders tells nothing about the body of subroutines.



Variable naming conventions: Be precise, if you are going to use Hungarian notation use it - FileSys should be changed to objFileSys.







share|improve this answer














share|improve this answer



share|improve this answer








edited Jul 25 '18 at 7:19

























answered Jul 24 '18 at 8:04









FlameHorizonFlameHorizon

436




436











  • thanks for you cleaner code the only thing there are also files that has not the sheet "Buitendelen" but only the sheet "Bezoekers registratie" is there a option to skip this file and go on to next on i think something like if workbook contains 1sheet skip if 2 do the thing
    – eVinx
    Jul 24 '18 at 17:19










  • There is not built in function which will allow to check if worksheet exists or not. I've updated my answer. If you find my reply useful, please mark my answer as "Answer". Also +1 is much appreciated :)
    – FlameHorizon
    Jul 25 '18 at 7:19










  • thanks in advance this works great :)
    – eVinx
    Jul 25 '18 at 15:59
















  • thanks for you cleaner code the only thing there are also files that has not the sheet "Buitendelen" but only the sheet "Bezoekers registratie" is there a option to skip this file and go on to next on i think something like if workbook contains 1sheet skip if 2 do the thing
    – eVinx
    Jul 24 '18 at 17:19










  • There is not built in function which will allow to check if worksheet exists or not. I've updated my answer. If you find my reply useful, please mark my answer as "Answer". Also +1 is much appreciated :)
    – FlameHorizon
    Jul 25 '18 at 7:19










  • thanks in advance this works great :)
    – eVinx
    Jul 25 '18 at 15:59















thanks for you cleaner code the only thing there are also files that has not the sheet "Buitendelen" but only the sheet "Bezoekers registratie" is there a option to skip this file and go on to next on i think something like if workbook contains 1sheet skip if 2 do the thing
– eVinx
Jul 24 '18 at 17:19




thanks for you cleaner code the only thing there are also files that has not the sheet "Buitendelen" but only the sheet "Bezoekers registratie" is there a option to skip this file and go on to next on i think something like if workbook contains 1sheet skip if 2 do the thing
– eVinx
Jul 24 '18 at 17:19












There is not built in function which will allow to check if worksheet exists or not. I've updated my answer. If you find my reply useful, please mark my answer as "Answer". Also +1 is much appreciated :)
– FlameHorizon
Jul 25 '18 at 7:19




There is not built in function which will allow to check if worksheet exists or not. I've updated my answer. If you find my reply useful, please mark my answer as "Answer". Also +1 is much appreciated :)
– FlameHorizon
Jul 25 '18 at 7:19












thanks in advance this works great :)
– eVinx
Jul 25 '18 at 15:59




thanks in advance this works great :)
– eVinx
Jul 25 '18 at 15:59

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51483174%2floop-through-directory-open-every-file-activate-sheet-and-add-new-column%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Use pre created SQLite database for Android project in kotlin

Darth Vader #20

Ondo