Can't pass variables from one sub to another in same module - vba

The code I have works great as separate procedures. I decided to combine the 2 procedures as the code is mostly the same with a few differences in which cells are copied to the array to save to different log sheets. Each Procedure has a Inputbox to get the year of interest (2014, 2015, 2016....) that will be used to open AND in the event the Log does not exist Save a new one from a master using the year code in the file name.
Based on a cell value I am doing an If_Then_Else to determine to run one procedure or both. If I run them separately as individual procedures they work fine. When I combined them I decided to call one procedure (SaveToLog_Audit) from inside (SaveToLog_Replc). I removed the Date input from (SaveToLog_Audit) letting (SaveToLog_Replc) get that date code and pass it along. I don't want to have (SaveToLog_Audit) ask for a date a second time as it run since I basically want it to be inobtrusive (no need to ask twice when I can pass Ans to it.
I have tried setting public Ans and used Explicit at the beginning with both procedures in same module --> didn't work. I tried Dim Ans As String after option Explicit --> Didn't work. I tried Public Ans as String --> didn't work. Pretty much I couldn't get it to pass the variable 'Ans" no matter what I tried. I'm still pretty new to coding VBA so any help would be great. Showing the basic code, only the parts that have issues.
Option Explicit
Public Ans As String
Public Sub SaveToLog_Replc()
' Determine scrap and whether to save to Replacement_Credit tracking log
Dim ScrapQty As Range
' Date entry for proper Dated log save
Dim Ans As String
Dim c As Boolean
Dim fs As Object
' Declares path, newFile and fName variables
Dim path As String, newFile As String, fName As String
Set Sheet2 = ActiveSheet
Set ScrapQty = Worksheets("Main").Range("M_Qty_Scrap")
Application.ScreenUpdating = False
' >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Ans = InputBox("Enter Log Year" & _
"" & vbCrLf, "Year Selection", Format(Date, "YYYY"))
If Ans = "" Then
Exit Sub
End If
' >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
' If scrap qty is greater than Zero (0) save to both Logs
If ScrapQty > 0 Then
' If True
MsgBox "Saving to Replacement Log and Audit Log"
' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
' Save to Audit Log then Save to Replacement Log
' --> 'Ans' VALUE NEEDS TO PASS TO THE PROCEDURE
' --> 'Ans' DOES NOT PASS TO THIS PROCEDURE AT END OF MODULE
Call SaveToLog_Audit
' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
' Sub routine to Save Data to Replacement Log
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' Load Array code here for SaveToLog_Replc
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' ***************************************************************
'Check if Replacement Log exists. If not open Master, rename then save it. If it exists open it.
Set fs = CreateObject("Scripting.FileSystemObject")
' Filename to check for
c = fs.fileExists("S:\RECORDS\Logs\Replacement Log " & Ans & ".xls")
If Not c Then
'MsgBox "The file doesn't exist!"
' File doesn't exist. Open the Blank Master
Workbooks.Open Filename:="S:\RECORDS\Logs\_MASTER Replacement Log.xls"
fName = "Replacement Log " & Ans & ".xls" ' Set fName to new FileName
newFile = fName ' Sets new filename as fName
path = "S:\RECORDS\Logs\" ' Path to Incoming Audit Logs
ActiveWorkbook.SaveAs Filename:=path & newFile ' Saves as newFile
Else
'MsgBox "The file exists! Saving data to it."
Workbooks.Open Filename:="S:\RECORDS\Logs\Replacement Log " & Ans & ".xls"
End If
' ***************************************************************
' Unprotect Sheet and Show All Data code here
' Find LastRow. Set NextCell position code here
' Set the size of the new array and copy MyAr code here
' Draw Border Code here
' **********************************************
ActiveWorkbook.Save ' Saves Destination Workbook
ActiveWindow.Close ' Closes Destination Workbook
Application.ScreenUpdating = True
' Confirms Save to Log File
MsgBox "Your Data has been saved to the Log File: " & vbCrLf & vbCrLf _
& "'Replacement Log " & Ans & ".xls'", vbInformation, "Log Save Confirmation"
' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Else
' If False
MsgBox "Saving to Audit Log Only."
' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
' Save to Audit Log as Normal
' --> 'Ans' VALUE NEEDS TO PASS TO THE PROCEDURE
' --> 'Ans' DOES NOT PASS TO THIS PROCEDURE AT END OF MODULE
Call SaveToLog_Audit
' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
End If
End Sub
Public Sub SaveToLog_Audit()
' Date entry for proper Dated log save
Dim Ans As String
Dim c As Boolean
Dim fs As Object
' Declares path, newFile and fName variables
Dim path As String, newFile As String, fName As String
Set Sheet2 = ActiveSheet
Application.ScreenUpdating = False
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' Load Array code here for SaveToLog_Audit
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' For debug
' --> 'Ans' DOES NOT PASS FROM (SaveToLog_Replc) PROCEDURE IN THIS MODULE
MsgBox "The value of Ans is: " & vbCrLf & vbCrLf & "'" & Ans & "'"
' ********************************************************
' Checks if Log File exists. If not open the Master, rename then save it. If it exists open it.
Set fs = CreateObject("Scripting.FileSystemObject")
' Filename to check for
c = fs.fileExists("S:\RECORDS\Logs\" & Ans & " Audit Log.xls")
If Not c Then
'MsgBox "The file doesn't exist!" original code
' File doesn't exist. Open the Blank Master
Workbooks.Open Filename:="S:\RECORDS\Logs\_Master Audit Log.xls"
' Set fName to new FileName
fName = Ans & " Audit Log.xls"
' Sets new filename as fName saves to this directory
newFile = fName
' Path to Incoming Audit Logs
path = "S:\RECORDS\Logs\"
' Saves Blank Master as newFile
ActiveWorkbook.SaveAs Filename:=path & newFile
Else
'Workbooks.Open "C:\filename.xls"
Workbooks.Open Filename:= _
"S:\RECORDS\Logs\" & Ans & " Audit Log.xls"
End If
' ********************************************************
' Unprotect Sheet and Show All Data code here
' Find LastRow. Set NextCell position code here
' Set the size of the new array and copy MyAr code here
' Draw Border Code here
' **********************************************
ActiveWorkbook.Save ' Saves Destination Workbook
ActiveWindow.Close ' Closes Destination Workbook
Application.ScreenUpdating = True
' Confirms Save to Log File
MsgBox "Your Data has been saved to the Log File: " & vbCrLf & vbCrLf _
& "'" & Ans & " Audit Log.xls'", vbInformation, "Log Save Confirmation"
End Sub

Are you running the code exactly as you posted? If yes then problem might be that you are delaring public ans then you are using dim ans in the first sub, later on you are assigning value to dim Ans not to public Ans those are made two separate variables. Remove the dim Ans from both subroutines and it should work

I suggest you remove the Public declaration and change the second routine to take a String argument:
Option Explicit
Public Sub SaveToLog_Replc()
' Determine scrap and whether to save to Replacement_Credit tracking log
Dim ScrapQty As Range
' Date entry for proper Dated log save
Dim Ans As String
Dim c As Boolean
Dim fs As Object
' Declares path, newFile and fName variables
Dim path As String, newFile As String, fName As String
Set Sheet2 = ActiveSheet
Set ScrapQty = Worksheets("Main").Range("M_Qty_Scrap")
Application.ScreenUpdating = False
' >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Ans = InputBox("Enter Log Year" & _
"" & vbCrLf, "Year Selection", Format(Date, "YYYY"))
If Ans = "" Then
Exit Sub
End If
' >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
' If scrap qty is greater than Zero (0) save to both Logs
If ScrapQty > 0 Then
' If True
MsgBox "Saving to Replacement Log and Audit Log"
' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
' Save to Audit Log then Save to Replacement Log
' --> 'Ans' VALUE NEEDS TO PASS TO THE PROCEDURE
' --> 'Ans' DOES NOT PASS TO THIS PROCEDURE AT END OF MODULE
Call SaveToLog_Audit(Ans)
' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
' Sub routine to Save Data to Replacement Log
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' Load Array code here for SaveToLog_Replc
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' ***************************************************************
'Check if Replacement Log exists. If not open Master, rename then save it. If it exists open it.
Set fs = CreateObject("Scripting.FileSystemObject")
' Filename to check for
c = fs.fileExists("S:\RECORDS\Logs\Replacement Log " & Ans & ".xls")
If Not c Then
'MsgBox "The file doesn't exist!"
' File doesn't exist. Open the Blank Master
Workbooks.Open Filename:="S:\RECORDS\Logs\_MASTER Replacement Log.xls"
fName = "Replacement Log " & Ans & ".xls" ' Set fName to new FileName
newFile = fName ' Sets new filename as fName
path = "S:\RECORDS\Logs\" ' Path to Incoming Audit Logs
ActiveWorkbook.SaveAs Filename:=path & newFile ' Saves as newFile
Else
'MsgBox "The file exists! Saving data to it."
Workbooks.Open Filename:="S:\RECORDS\Logs\Replacement Log " & Ans & ".xls"
End If
' ***************************************************************
' Unprotect Sheet and Show All Data code here
' Find LastRow. Set NextCell position code here
' Set the size of the new array and copy MyAr code here
' Draw Border Code here
' **********************************************
ActiveWorkbook.Save ' Saves Destination Workbook
ActiveWindow.Close ' Closes Destination Workbook
Application.ScreenUpdating = True
' Confirms Save to Log File
MsgBox "Your Data has been saved to the Log File: " & vbCrLf & vbCrLf _
& "'Replacement Log " & Ans & ".xls'", vbInformation, "Log Save Confirmation"
' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Else
' If False
MsgBox "Saving to Audit Log Only."
' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
' Save to Audit Log as Normal
' --> 'Ans' VALUE NEEDS TO PASS TO THE PROCEDURE
' --> 'Ans' DOES NOT PASS TO THIS PROCEDURE AT END OF MODULE
Call SaveToLog_Audit(Ans)
' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
End If
End Sub
Public Sub SaveToLog_Audit(Ans As String)
' Date entry for proper Dated log save
Dim c As Boolean
Dim fs As Object
' Declares path, newFile and fName variables
Dim path As String, newFile As String, fName As String
Set Sheet2 = ActiveSheet
Application.ScreenUpdating = False
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' Load Array code here for SaveToLog_Audit
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
' For debug
' --> 'Ans' DOES NOT PASS FROM (SaveToLog_Replc) PROCEDURE IN THIS MODULE
MsgBox "The value of Ans is: " & vbCrLf & vbCrLf & "'" & Ans & "'"
' ********************************************************
' Checks if Log File exists. If not open the Master, rename then save it. If it exists open it.
Set fs = CreateObject("Scripting.FileSystemObject")
' Filename to check for
c = fs.fileExists("S:\RECORDS\Logs\" & Ans & " Audit Log.xls")
If Not c Then
'MsgBox "The file doesn't exist!" original code
' File doesn't exist. Open the Blank Master
Workbooks.Open Filename:="S:\RECORDS\Logs\_Master Audit Log.xls"
' Set fName to new FileName
fName = Ans & " Audit Log.xls"
' Sets new filename as fName saves to this directory
newFile = fName
' Path to Incoming Audit Logs
path = "S:\RECORDS\Logs\"
' Saves Blank Master as newFile
ActiveWorkbook.SaveAs Filename:=path & newFile
Else
'Workbooks.Open "C:\filename.xls"
Workbooks.Open Filename:= _
"S:\RECORDS\Logs\" & Ans & " Audit Log.xls"
End If
' ********************************************************
' Unprotect Sheet and Show All Data code here
' Find LastRow. Set NextCell position code here
' Set the size of the new array and copy MyAr code here
' Draw Border Code here
' **********************************************
ActiveWorkbook.Save ' Saves Destination Workbook
ActiveWindow.Close ' Closes Destination Workbook
Application.ScreenUpdating = True
' Confirms Save to Log File
MsgBox "Your Data has been saved to the Log File: " & vbCrLf & vbCrLf _
& "'" & Ans & " Audit Log.xls'", vbInformation, "Log Save Confirmation"
End Sub

Related

Error Message Occurs in Saving Excel Files when I use Excel VBA Function

When I try to save the below code it gives an error message and I can't save it.
below are my error message's image file link.
I'm using Korean Excel 2007, So I don't know what exactly this message is in English but I can give you the meaning of this error message.
(this error message means... couldn't find file.)
(this error message means.... &H8000FFFF system error occurs.)
(I tried Export UserForm File but there were same error messages.)
I tried opening another Excel Window and Pasting Userforms, exporting Userform as files, saving as a different name and saving to a different path, but I kept getting the same error message.
I updated My windows7 to latest version in several days ago.
Below is part of code for sending Email From Excel (All code couldn't upload. It is so long and considered as spam.) and I uploaded UserForm ScreenShots For your Reference.
-----------My Part of Code And UserForm
My UserForm
Function NPP메일보내기함수()
'//ThisWorkbook.SaveAs ThisWorkbook.Path & "\" & Date & " " & "Position Report Ver.2.xlsx", FileFormat:=51 '//xlsm은 52
'//위 방법은 xlsx 저장은 잘 되나 아래와 같은 문제가 있다.
'//I have a Excel sheet, and if I save the file using the Save as... option in Excel VBA the currently open document would close, and switch over to the newly created document.
'//How can I save a copy of the document without switching over the control?
'//해결하려면 여러가지 방법이 있다. 여기엔 하나만 적는다. 아래와 같이 하는건 잘못된 방법이다. SaveCopyAS는 확장자 못 바꿈.
'//ThisWorkbook.SaveCopyAs ThisWorkbook.Path & "\" & Date & " " & "Position Report Ver.2 MEIN.xlsx" '//, FileFormat:=51
'//위 방법은 새창으로 안 열리기는 하나 확장자가 안 바뀜.
'//아래 방법이 새창으로 안 열리면서 확장자도 바뀌는 완벽한 방법임.
'
' Dim wb As Workbook, pstr As String
'
' pstr = ThisWorkbook.Path & "\" & Date & " Position Report Ver. 02 MEIN" & ".xlsm"
' ActiveWorkbook.SaveCopyAs Filename:=y
'
' Set wb = Workbooks.Open(pstr)
' wb.SaveAs Left(pstr, Len(pstr) - 1) & "x", 52
' wb.Close False
'
' Kill pstr
' 오류뜸
'//http://www.excely.com/excel-vba/save-workbook-as-new-file.shtml
ThisWorkbook.Sheets.Copy
Application.DisplayAlerts = False
Dim 매크로파일경로 As String
매크로파일경로 = ThisWorkbook.Path
ActiveWorkbook.SaveAs 매크로파일경로 & "\눈레포트 첨부 엑셀파일\" & Format(Date, "yyyy-mm-dd") & " " & "Position Report Ver.3 MEIN.xlsx", FileFormat:=51
ActiveWorkbook.Close
On Error GoTo Error_Handler
Dim oOutlook As Object
Dim sAPPPath As String
If IsAppRunning("Outlook.Application") = True Then 'Outlook was already running
Set oOutlook = GetObject(, "Outlook.Application") 'Bind to existing instance of Outlook
Else 'Could not get instance of Outlook, so create a new one
sAPPPath = GetAppExePath("outlook.exe") 'determine outlook's installation path
Shell (sAPPPath) 'start outlook
Do While Not IsAppRunning("Outlook.Application")
DoEvents
Loop
Set oOutlook = GetObject(, "Outlook.Application") 'Bind to existing instance of Outlook
End If
' MsgBox "Outlook Should be running now, let's do something"
Const olMailItem = 0
Dim oOutlookMsg As Object
Set oOutlookMsg = oOutlook.CreateItem(olMailItem) 'Start a new e-mail message
Dim 보낼메세지 As String
Dim 반복문카운터 As Integer
For 반복문카운터 = 95 To 127
보낼메세지 = 보낼메세지 & ThisWorkbook.Worksheets("NPP").Range("C" & 반복문카운터).Value & Chr(13) & Chr(10)
Next
With oOutlookMsg
.To = "해사운항팀"
.CC = " 사업안전팀; 최종범차장; 조달팀; 공무팀; 사업팀; 박준영대리; 고현해운"
.BCC = ""
.Subject = Range("C99").Value
'// .Body = Range("C95:C127").Value 요렇게 하면 안돼요.
.Body = 보낼메세지
'//Attachments를 Attachment라고 써서 에러가 나던 것.
.Attachments.Add 매크로파일경로 & "\눈레포트 첨부 엑셀파일\" & Format(Date, "yyyy-mm-dd") & " " & "Position Report Ver.3 MEIN.xlsx"
'//ThisWorkbook.Path하니까 파일이 없다는 오류가 나서 시도해봄.
.Display 'Show the message to the user
End With
Error_Handler_Exit:
On Error Resume Next
Set oOutlook = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: StartOutlook" & vbCrLf & _
"Error Description: " & Err.Description _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function
'---------------------------------------------------------------------------------------
' Procedure : IsAppRunning
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Determine is an App is running or not
' Copyright : The following may be altered and reused as you wish so long as the
' copyright notice is left unchanged (including Author, Website and
' Copyright). It may not be sold/resold or reposted on other sites (links
' back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sApp : GetObject Application to verify if it is running or not
'
' Usage:
' ~~~~~~
' IsAppRunning("Outlook.Application")
' IsAppRunning("Excel.Application")
' IsAppRunning("Word.Application")
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2014-Oct-31 Initial Release
'---------------------------------------------------------------------------------------
Function IsAppRunning(sApp As String) As Boolean
On Error GoTo Error_Handler
Dim oApp As Object
Set oApp = GetObject(, sApp)
IsAppRunning = True
Error_Handler_Exit:
On Error Resume Next
Set oApp = Nothing
Exit Function
Error_Handler:
Resume Error_Handler_Exit
End Function
'---------------------------------------------------------------------------------------
' Procedure : GetAppExePath
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Determine the path for a given exe installed on the local computer
' Copyright : The following may be altered and reused as you wish so long as the
' copyright notice is left unchanged (including Author, Website and
' Copyright). It may not be sold/resold or reposted on other sites (links
' back to this site are allowed).
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sEXEName : Name of the exe to locate
'
' Usage:
' ~~~~~~
' Call GetAppExePath("msaccess.exe")
' GetAppExePath("firefox.exe")
' GetAppExePath("outlook.exe")
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2014-Oct-31 Initial Release
'---------------------------------------------------------------------------------------
Function GetAppExePath(ByVal sExeName As String) As String
On Error GoTo Error_Handler
Dim WSHShell As Object
Set WSHShell = CreateObject("Wscript.Shell")
GetAppExePath = WSHShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\" & sExeName & "\")
Error_Handler_Exit:
On Error Resume Next
Set WSHShell = Nothing
Exit Function
Error_Handler:
If Err.Number = -2147024894 Then
'Cannot locate requested exe????
Else
MsgBox "The following error has occured." & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: GetAppExePath" & vbCrLf & _
"Error Description: " & Err.Description, _
vbCritical, "An Error has Occured!"
End If
Resume Error_Handler_Exit
End Function

Export Module Using Macro

I'm stepping through the code to export a module using this post, but nothing happens. Is there a security setting to allow VBA permission to export a module?
I'm copying a few tabs from a workbook into a new workbook, but the tabs have macros which lead to broken links. To get around this I want to move the module and re-associate the macro. If I can't get this to work I will just copy the whole workbook and delete the info I don't want in the destination.
Here's the code from the above post:
Public Sub CopyModule(SourceWB As Workbook, strModuleName As String, TargetWB As Workbook)
' Description: copies a module from one workbook to another
' example: CopyModule Workbooks(ThisWorkbook), "Module2",
' Workbooks("Food Specials Rolling Depot Memo 46 - 01.xlsm")
' Notes: If Module to be copied already exists, it is removed first,
' and afterwards copied
Dim strFolder As String
Dim strTempFile As String
Dim FName As String
If Trim(strModuleName) = vbNullString Then
Exit Sub
End If
If TargetWB Is Nothing Then
MsgBox "Error: Target Workbook " & TargetWB.Name & " doesn't exist (or closed)", vbCritical
Exit Sub
End If
strFolder = SourceWB.Path
If Len(strFolder) = 0 Then strFolder = CurDir
' create temp file and copy "Module2" into it
strFolder = strFolder & "\"
strTempFile = strFolder & "~tmpexport.bas"
On Error Resume Next
FName = Environ("Temp") & "\" & strModuleName & ".bas"
If Dir(FName, vbNormal + vbHidden + vbSystem) <> vbNullString Then
Err.Clear
Kill FName
If Err.Number <> 0 Then
MsgBox "Error copying module " & strModuleName & " from Workbook " & SourceWB.Name & " to Workbook " & TargetWB.Name, vbInformation
Exit Sub
End If
End If
' remove "Module2" if already exits in destination workbook
With TargetWB.VBProject.VBComponents
.Remove .Item(strModuleName)
End With
' copy "Module2" from temp file to destination workbook
SourceWB.VBProject.VBComponents(strModuleName).Export strTempFile
TargetWB.VBProject.VBComponents.Import strTempFile
Kill strTempFile
On Error GoTo 0
End Sub

VBA macro that copy files from multiple subfolders

I have a VBA for copying images from one folder to another based on image names. You can check macro in work in attached. Code is:
Option Explicit
Sub CopyFiles()
Dim iRow As Integer ' ROW COUNTER.
Dim sSourcePath As String
Dim sDestinationPath As String
Dim sFileType As String
Dim bContinue As Boolean
bContinue = True
iRow = 2
' THE SOURCE AND DESTINATION FOLDER WITH PATH.
sSourcePath = "C:\Users\nhatc_000\Desktop\01010101\"
sDestinationPath = "C:\Users\nhatc_000\Desktop\02020202\"
sFileType = ".jpg" ' TRY WITH OTHER FILE TYPES LIKE ".pdf".
' LOOP THROUGH COLUMN "A" TO PICK THE FILES.
While bContinue
If Len(Range("A" & CStr(iRow)).Value) = 0 Then ' DO NOTHING IF THE COLUMN IS BLANK.
MsgBox "Images have been moved. Thank you!" ' DONE.
bContinue = False
Else
' CHECK IF FILES EXISTS.
If Len(Dir(sSourcePath & Range("A" & CStr(iRow)).Value & sFileType)) = 0 Then
Range("B" & CStr(iRow)).Value = "Does Not Exists"
Range("B" & CStr(iRow)).Font.Bold = True
Else
Range("B" & CStr(iRow)).Value = "On Hand"
Range("B" & CStr(iRow)).Font.Bold = False
If Trim(sDestinationPath) <> "" Then
Dim objFSO
Set objFSO = CreateObject("scripting.filesystemobject")
' CHECK IF DESTINATION FOLDER EXISTS.
If objFSO.FolderExists(sDestinationPath) = False Then
MsgBox sDestinationPath & " Does Not Exists"
Exit Sub
End If
'*****
' HERE I HAVE INCLUDED TWO DIFFERENT METHODS.
' I HAVE COMMENTED THE SECOND METHOD. TO THE SEE THE RESULT OF THE
' SECOND METHOD, UNCOMMENT IT AND COMMENT THE FIRST METHOD.
' METHOD 1) - USING "CopyFile" METHOD TO COPY THE FILES.
objFSO.CopyFile Source:=sSourcePath & Range("A" & CStr(iRow)).Value & _
sFileType, Destination:=sDestinationPath
' METHOD 2) - USING "MoveFile" METHOD TO PERMANENTLY MOVE THE FILES.
'objFSO.MoveFile Source:=sSourcePath & Range("B" & CStr(iRow)).Value & _
sFileType, Destination:=sDestinationPath
'*****
End If
End If
End If
iRow = iRow + 1 ' INCREMENT ROW COUNTER.
Wend
End Sub
However, I need 2 more things to add to this code:
When I enter the name of the file to be copied, I also want to copy
files that have the same name PLUS extension _01/_02/.../_07 if
those exist.
I want macro to look not only inside specified folder but also in
subfolders inside the folder and subfolders inside the subfolder
etc.
Can anyone help?
Thanks!
What you need is some Recursive Subs to find all the similar filenames based on the Range value.
Here I will approach this goal with below code with a couple of steps:
For each Range value (stored as a Key in Dictionary), find all the file names (exact and similar as Item in Dictionary). Joining each finding with "|" (an illegal file name character).
Process the Dictionary items after all files and sub folders from Source Path
For each Item in the dictionary of a key, see if existing file in destination folder. Append " (i)" to destination file name if already exists.
Copy the destination file to destination folder.
While copying, it returns the
Stop looping when first Empty cell is encountered
NOTE: Code not been tested, only compiled fine
Option Explicit
' THE SOURCE AND DESTINATION FOLDER WITH PATH.
Private Const sSourcePath = "C:\Users\nhatc_000\Desktop\01010101\"
Private Const sDestinationPath = "C:\Users\nhatc_000\Desktop\02020202\"
Private Const sFileType = "jpg" ' TRY WITH OTHER FILE TYPES LIKE ".pdf".
Private Const DIV = "|" ' A character that's not legal file name
Private objFSO As Object, objDict As Object
Sub CopyFilesAlike()
Dim lRow As Long, sName As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(sSourcePath) Then
MsgBox "Source folder not found!" & vbCrLf & sSourcePath, vbCritical + vbOKOnly
GoTo I_AM_DONE
End If
If Not objFSO.FolderExists(sDestinationPath) Then
MsgBox "Destination folder not found!" & vbCrLf & sDestinationPath, vbCritical + vbOKOnly
GoTo I_AM_DONE
End If
' Proceed when both Source and Destination folders found
Set objDict = CreateObject("Scripting.Dictionary")
lRow = 2
Do Until IsEmpty(Cells(lRow, "A")) ' Stop on first empty cell in Column A from lRow
' Get Main file name to look up
sName = Cells(lRow, "A").Value
' Look for files (exact and alikes from sub folders) to add to dictionary
LookForFilesAlike sName, objFSO.GetFolder(sSourcePath)
' Copy files
If objDict.Count = 0 Then
Cells(lRow, "B").Value = "No files found."
Else
Cells(lRow, "B").Value = objDict.Count & " filenames(s) found." & vbLf & CopyFiles
End If
' Clear the Dictionary for next Name
objDict.RemoveAll
' Increment row counter
lRow = lRow + 1
Loop
Set objDict = Nothing
I_AM_DONE:
Set objFSO = Nothing
End Sub
Private Sub LookForFilesAlike(ByVal sName As String, ByVal objFDR As Object)
Dim oFile As Object, oFDR As Object
' Add files of current folder to dictionary if name matches
For Each oFile In objFDR.Files
If InStr(1, oFile.Name, sName, vbTextCompare) = 1 Then ' Names beginning with sName
' Check the extension to match
If LCase(objFSO.GetExtensionName(oFile)) = LCase(sFileType) Then
If objDict.Exists(oFile.Name) Then
' Append Path to existing entry
objDict.Item(oFile.Name) = objDict.Item(oFile.Name) & DIV & oFile.Path
Else
' Add Key and current path
objDict.Add oFile.Name, oFile.Path
End If
End If
End If
Next
' Recurse into each sub folder
For Each oFDR In objFDR.SubFolders
LookForFilesAlike sName, oFDR
Next
End Sub
Private Function CopyFiles() As String
Dim i As Long, oKeys As Variant, oItem As Variant, iRepeat As Integer, sName As String, sOut As String
sOut = ""
' Process the items for each key in Dictionary
Set oKeys = objDict.Keys ' <- Add "Set " before oKeys
For i = 0 To objDict.Count
For Each oItem In Split(objDict.Item(oKeys(i)), DIV)
' Determine the filename in destination path
If objFSO.FileExists(sDestinationPath & objFSO.GetFileName(oItem)) Then
' Same file name alreay found, try append " (i)"
iRepeat = 0
Do
iRepeat = iRepeat + 1
sName = objFSO.GetBaseName(oItem) & " (" & iRepeat & ")" & objFSO.GetExtensionName(oItem)
Loop While objFSO.FileExists(sDestinationPath & sName)
sName = sDestinationPath & sName
Else
' First file to be copied to destination folder
sName = sDestinationPath
End If
' Copy the source file to destination file
If Len(sOut) = 0 Then
sOut = oItem & DIV & sName
Else
sOut = sOut & vbLf & oItem & DIV & sName
End If
objFSO.CopyFile oItem, sName
Next
Next
CopyFiles = sOut
End Function

VBA to save worksheet with a specific name

Hi probably a simple answer but im new to VBA.
I have a worksheet in a workbook. This worksheet has a specific reference in cell A1 which changes each time its used. It is basically an order number and formatted 03 01 15. The next will be 03 02 15, then 03 03 15 and so on.
What I want to do is to use VBA to save the sheet in a new workbook in my orders folder, and for the new workbook to be called the order number.
I can use the record macro function to get the basic VBA to copy the sheet, open a new workbook, paste the values and close the workbook, but im struggling with getting the name right. Each new workbook will have a different name based on the order number.
Any help would be appriciated.
Export a Worksheet to a Folder
Sub ExportWorksheetToFolder()
Const ProcTitle As String = "Export Worksheet to Folder"
' Define constants.
Const DESTINATION_SUBFOLDER_NAME As String = "Orders"
Const DESTINATION_FILE_NAME_ADDRESS As String = "A1"
' Reference the worksheet.
Dim ws As Worksheet: Set ws = ActiveSheet
' Instead, improve with e.g.
'Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
' Build the destination file path ('dFilePath').
' Since we will be saving an unsaved workbook (file), by not supplying
' the file extension and the parameter for the FileFormat argument
' of the SaveAs method, the new workbook will be saved
' with the .xlsx extension (losing any code in it) or,
' for Office prior to version 2007, with the .xls extension.
Dim pSep As String: pSep = Application.PathSeparator
' If the cell is blank, we don't have a name.
Dim dBaseName As String
dBaseName = CStr(ws.Range(DESTINATION_FILE_NAME_ADDRESS))
If Len(dBaseName) = 0 Then
MsgBox "Cell " & UCase(DESTINATION_FILE_NAME_ADDRESS) & " is blank.", _
vbCritical, ProcTitle
Exit Sub
End If
' If the workbook has never been saved, its path is "".
Dim wbPath As String: wbPath = ws.Parent.Path
If Len(wbPath) = 0 Then
MsgBox "You need to save the workbook to use this procedure.", _
vbCritical, ProcTitle
Exit Sub
End If
' Create the subfolder if it doesn't exist.
Dim dFolderPath As String: dFolderPath = wb.Path _
& pSep & DESTINATION_SUBFOLDER_NAME & pSep
If Len(Dir(dFolderPath, vbDirectory)) = 0 Then MkDir dFolderPath
Dim dFilePath As String: dFilePath = dFolderPath & dBaseName
' Copy.
ws.Copy ' copies the worksheet to a new workbook
' Save.
Dim MsgString As String
With Workbooks(Workbooks.Count) ' reference the new workbook
Application.DisplayAlerts = False
' 1. save without macros ... without confirmation
' 2. overwrite existing file ... without confirmation
On Error Resume Next
.SaveAs dFilePath
If Err.Number <> 0 Then ' invalid file name, file open...
MsgString = "Run-time error '" & Err.Number & "':" _
& vbLf & vbLf & Err.Description _
& vbLf & vbLf & "Could not save as '" & dFilePath & "'."
End If
On Error GoTo 0
Application.DisplayAlerts = True
.Close SaveChanges:=False
End With
' Inform.
If Len(MsgString) = 0 Then
MsgBox "Worksheet exported.", vbInformation, ProcTitle
Else
MsgBox MsgString, vbCritical, ProcTitle
End If
End Sub

Save an Excel file and export it to pdf with a different sheet

I have never written VBA code, but I checked on internet for some information.
My wish is the following: I have an Excel file with 3 sheets. On one of them, I'd like to add one button which can:
Save the totality of my Excel file following this naming convention: [name of a cells of a page]_AP_[date of today].xls.
Save one of the sheets in a .pdf file.
Print 2 of the 3 sheets while adjusting the contents.
I already started something, but I'm really bad at programming:
Public Sub Savefile_Click() 'copie sauvegarde classeur
' save my file following a name
Dim nom As String
Dim chemin As String
Dim wSheet As Worksheet
chemin = "C:\Users\aaa\Desktop"
nom = [Q13].Value & "_" & Day(Date) & "-" & Month(Date) & "-" & Year(Date) _
& ".xlsm"
With ActiveWorkbook
.SaveAs Filename:=chemin & nom
.Close
rep = MsgBox("Fichier excell sauvegardé")
End With
' ... and print my active sheet (where the button will stay)
For Each wSheet In ActiveWorkbook.Worksheets
If wSheet.Visible Then wSheet.PrintOut
Next
'Save my page 'offre' in pdf on my desktop and print it
Worksheets("OFFRE A ENVOYER").Range("A1:i47").ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=[Q13].Value & "_Offre de prix", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
After that there will be another option and details, but this is really the base.
1) Save as Excel
Dim nom As String
nom = ThisWorkbook.Sheets(1).Range("Q13").Value & "AP" & Format(Date, "ddmmyyyy") & ".xls"
thisworkbook.saveas sPath & nom 'Define path first, don't forget the \ at the end.
Even better would be to create a named range from range "Q13" and use:
nom = thisworkbook.names("Something").referstorange.value
To make the link dynamic in case you insert a column or row which shifts all your ranges.
2) Save workbook as PDF
ThisWorkbook.ExportAsFixedFormat xlTypePDF, sPath & sFile 'Define here .pdf
3)
"print 2 of the 3sheets with adjusting the contenant of a "
I'm not sure if I get this one...
Print command is given by:
Set oSheet= thisworkbook.sheets(2)
with oSheet.PageSetup
.PrintArea = "$A1$1:$Q$40"
...
'Any other properties: http://www.java2s.com/Code/VBA-Excel-Access-Word/Excel/AllpropertiesofPageSetup.htm
end with
oSheet.printout
Which ever way you want to program this in order to retrieve the sheets that you need to print.
You can loop through the sheets with a counter and put if statements to add conditions.
dim oSheet as Excel.worksheet
dim iCnt as integer
For each oSheet in thisworkbook.sheets
iCnt = iCnt + 1
'Include conditions here
If ... then 'Whatever condition
set oSheet = thisworkbook.sheets(iCnt)
'Print
end if
next oSheet
thank you ...i was searching this. this worked very well.
Option Explicit
Sub SvMe() 'Save filename as value of A1 plus the current date
Dim newFile As String, fName As String
' Don't use "/" in date, invalid syntax
fName = Range("A1").Value
newFile = fName & " " & Format$(Date, "mm-dd-yyyy")
' Change directory to suit
ChDir _
"C:\Users\user\Desktop" 'YOU MUST Change USER NAME to suit
ThisWorkbook.ExportAsFixedFormat xlTypePDF, Filename:=newFile
End Sub
this
1. saves my file in pdf format and
2. does not prompt me for attending save as dialog box
3. saves file using cell value in A1 and date stamp