View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
NickHK NickHK is offline
external usenet poster
 
Posts: 4,391
Default Open a sheet rename and move to another workbook

Patrick,
You need to get the next available file to work on:
Do While TheFile < ""
Set wb = Workbooks.Open(MyPath & "\" & TheFile)
ActiveSheet.Name = ActiveWorkbook.Name
ActiveSheet.Move After:=Workbooks("Book2").Sheets(Sheets.Count)
TheFile =Dir() '<<<
Loop

Also you have the WB reference so why not use it to make it more clear which
workbook/sheet you are working on.
Also, how do you know what the ActiveSheet of the open workbook is ? It will
depend which was active when the workbook was last closed.
It would better to close the WB if you are finished to avoid having a lot of
open workbooks.

Do While TheFile < ""
Set WB = Workbooks.Open(MyPath & "\" & TheFile)
With WB.WorkSheets(1)
.Name = WB.Name
.Move After:=Workbooks("Book2").Sheets(Sheets.Count)
End With
WB.Close True/False
TheFile =Dir() '<<<
Loop


"Patrick" wrote in message
...
Ok,
I have gotten the code below to work BUT it loops on the same file

instead
of moving on to the next file. My goal is to open all the files in a
particular directory, renmae the worksheet with the file name and then

move
that worksheet to the workbook which the macro is running from i.e. in

this
case book2.
Any fix for the incorrect looping?
Only learning here and so need a lot of help
Patrick


Sub AllFolderFiles()
Dim wb As Workbook
Dim TheFile As String
Dim MyPath As String
MyPath = "F:\Work Stuff 2\Work Stuff\Promotion Report"
ChDir MyPath
TheFile = Dir("*.xls")
Do While TheFile < ""
Set wb = Workbooks.Open(MyPath & "\" & TheFile)
ActiveSheet.Name = ActiveWorkbook.Name
ActiveSheet.Move After:=Workbooks("Book2").Sheets(Sheets.Count)
Loop
End Sub