View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Norman Jones[_2_] Norman Jones[_2_] is offline
external usenet poster
 
Posts: 421
Default Open files with a variable name in a folder get name in B1 and sav

Hi Les,

You could use the FileSysyemObject to
each file.

To read the cell value from each closed file,
I use John Walkenbach's GetValue function
(http://www.j-walk.com/ss/excel/tips/tip82.htm)

In a standard module, paste the follwing code:

'===========
Option Explicit

'--------------
Private Sub RenameFiles()
Dim oFSO As Object
Dim oFolder As Object
Dim ofile As Object
Dim oFiles As Object
Dim sPath As String
Dim sName As String
Dim Res As String
Const sSheet As String = "Sheet1" '<<===== CHANGE
Const sCell As String = "A1" '<<===== CHANGE

sPath = "C:\Users\Norman\" _
& "Documents\Test" '<<===== CHANGE

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files

For Each ofile In oFiles
With ofile
sName = .Name
Res = GetValue(sPath, sName, sSheet, sCell)
Name sName As Res & ".xls"
End With
Next ofile

End Sub

'------------
Private Function GetValue(path, file, sheet, ref)
'======================
'\\ John Walkenbach
'\\ http://www.j-walk.com/ss/excel/tips/tip82.htm
'\\ Retrieves a value from a closed workbook
'======================
Dim arg As String

' Make sure the file exists
If Right(path, 1) < "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If

' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)

' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
'<===========



---
Regards.
Norman


"Les" wrote in message
...
Hi all, i need to loop through a folder and open all the "xls" files one
by
one, get the name from "B1" and then save the file back to the same folder
with the name obtained. Lastley I then need to delete the original file.

Any help with code would be appreciated

--
Les