Hi,
I am trying to add a Prefix string (with if condition) to the current filename and overwrite at the same location as the current file. A certain Prefix is appended to the current filename if the filename contains a partciular string such as 0915 or 1215, etc, then the file name is overwritten and saved and then moved to next file in the directory.
However, I am not getting any result and its not working, may be its having trouble with Prefix declaration, but I can't figure it out as per my very limited excel vba knowledge. How can I make it work? For which reason it isn't working, this code? The vba code is pasted below:
Sub ChangeFilename()
Dim mybook As Workbook
Dim MyPath As String, FilesInPath As String
Dim MyFiles() As String, Prefix As Variant
Dim MyFile As String, FNum As Long, fMame As String
MyPath = "C:\data2\one"
' Add a slash at the end of path if needed.
If Right(MyPath, 1) <> "\" Then
MyPath = MyPath & "\"
End If
' If there are no Excel files in the folder, exit.
FilesInPath = Dir(MyPath & "*.xlsx*")
If FilesInPath = "" Then
MsgBox "No files found"
Exit Sub
End If
' Fill in the myFiles array with the list of Excel files in
' the search folder.
FNum = 0
Do While FilesInPath <> ""
FNum = FNum + 1
ReDim Preserve MyFiles(1 To FNum)
MyFiles(FNum) = FilesInPath
FilesInPath = Dir()
Loop
If FNum > 0 Then
For FNum = LBound(MyFiles) To UBound(MyFiles)
Set mybook = Nothing
On Error Resume Next
Set mybook = Workbooks.Open(MyPath & MyFiles(FNum))
On Error GoTo 0
sFileName = mybook.FullName
If InStr(1, sFileName, "0915", vbTextCompare) > 0 Then
Prefix = "SRJ1"
ElseIf InStr(1, sFileName, "1215", vbTextCompare) > 0 Then
Prefix = "SRJ2"
ElseIf InStr(1, sFileName, "1315", vbTextCompare) > 0 Then
Prefix = "SRJ3"
ElseIf InStr(1, sFileName, "1515", vbTextCompare) > 0 Then
Prefix = "SRJ4"
ElseIf InStr(1, sFileName, "1715", vbTextCompare) > 0 Then
Prefix = "SRJ5"
ElseIf InStr(1, sFileName, "2315", vbTextCompare) > 0 Then
Prefix = "SRJ6"
ElseIf InStr(1, sFileName, "0900", vbTextCompare) > 0 Then
Prefix = "SRJ7"
ElseIf InStr(1, sFileName, "1200", vbTextCompare) > 0 Then
Prefix = "SRJ8"
ElseIf InStr(1, sFileName, "1800", vbTextCompare) > 0 Then
Prefix = "SRJ9"
End If
mybook.Activate
fName = Prefix & sFileName & ".xlsx"
ActiveWorkbook.SaveAs ActiveWorkbook.Path & fName
mybook.Close
Next FNum
End If
End Sub
Thanks for your help.
Sanjeev.
Bookmarks