Public Sub One()
Dim varStar
Dim varStars
varStar = Array("Rain", "Sleet", "Snow")
For each varStar in varStars
Call Precipitation (varStar)
Call Monthly (varStar)
Call Weekly (varStar)
Call Yearly (varStar)
Next varStar
End Sub
Public Sub Monthly (varStar)
On Error Resume Next
Set WB = Workbooks.Open(Filename:="" & varStar)
Run "RefreshOnOpen"
With WB
WB.SaveAs Filename:=""
End With
WB.Close
On Error GoTo 0
End Sub
And then from there it will call the corresponding module and pass varStar to each module and run the code. The issue I have is that sometimes (like right now) it is a new year, or a new month and varStar may not exist in the specific workbook. How can I code it to, if varStar doesn't exist just skip it and keep going. I tried On Error Resume Next, and On Error GoTo 0. But that wasn't 100% efficient. If you need to see additional coding, let me know, and I can provide more.
you can not saveAs with no valid filename, error will occur, also the with block here is not used at all (with and end with can be totally removed)
varStar = Array("Rain", "Sleet", "Snow")
For each varStar in varStars
the array should be named varstars, so you can loop through it, otherwise it should be for each somevar in varstar
another method to deal with sheet missing
vb Code:
on error resume next ' start inline error handling
set sht = sheets(varstar)
if not err.number = 0 then ' an error occured
' create new sheet
end if
on error goto 0 ' turn off inline error handling
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case. Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
Public Sub Monthly (varStar)
On Error Resume Next
Set WB = Workbooks.Open(Filename:="" & varStar)
Call DoesWorkSheetExist
Run "RefreshOnOpen"
With WB
WB.SaveAs Filename:=""
End With
WB.Close
On Error GoTo 0
End Sub
I get a debug error of Argument not optional on the function posted here? Did I place it in the wrong place or leave out something?
Last edited by Jo15765; Jan 16th, 2012 at 09:20 AM.
you can not saveAs with no valid filename, error will occur,
from my previous post
an empty string is not a valid filename
i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case. Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next
dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part
come back and mark your original post as resolved if your problem is fixed
pete
I am kind of confused. Your Post Title says that you want to check if a workbook exists or not and in your post you are checking for the worksheets? I believe that you might be checking for worksheets...
There are lot of things in your code that I want to refer to. So let's go through them one by one
In my below code, I am checking for both the Workbook and WorkSheet if they exists or not.
1) You don't need to open the workbook to check if the file exists or not.
2) You are trying to open a file without specifying the path and the extension?
3) When Saving File you have to specify the Path, Newname, File Extension and then FileFormat. (Especially if you are using Excel 2007 onwards)
4) I have not covered error handling. What I would recommend is having a look at this link.
I have commented the code thoroughly so you should not have a problem in understanding it.
Code:
Option Explicit
'~~> Change File Path of the workbook Here
Const FilePath As String = "C:\Temp\"
'~~> Change File Extenstion of the workbook here
Const FileExt As String = ".xls"
'~~> File Which you have to open
Const FileName As String = "Temp"
'~~> THE ABOVE WILL BE USED IF YOU ARE ACTUALLY DOING A SAVEAS
Dim Wb As Workbook
Dim ws As Worksheet
Public Sub One()
Dim varStar, varStars
varStars = Array("Rain", "Sleet", "Snow")
For Each varStar In varStars
Call Precipitation(varStar)
Call Monthly(varStar)
Call Weekly(varStar)
Call Yearly(varStar)
Next varStar
End Sub
Public Sub Monthly(varStar)
Dim NewName As String
Dim Filefrmt As Long
'~~> New Name for the File (Will be required if you are doing a SAVE AS
NewName = "NewRain"
'~~> Check if the workbook exists
If FileExists(FilePath & FileName & FileExt) Then
'~~> If exists, open it
Set Wb = Workbooks.Open(FilePath & FileName & FileExt)
'~~> Check if Sheet exists
If SheetExists(varStar) Then
Run "RefreshOnOpen"
'~~> Comment the below 6 lines if you are not doing a SAVE AS
Select Case FileExt
Case ".xls": Filefrmt = 56
Case ".xlsx": Filefrmt = 51
Case ".xlsm": Filefrmt = 52
Case ".xlsb": Filefrmt = 50
End Select
With Wb
.SaveAs FilePath & NewName & FileExt, Filefrmt
.Close SaveChanges:=False
'--------------- NOTE ---------------
'~~> If you are just trying to save the existing file then you do not need a SaveAs
'~~> Comment the above two lines and uncomment the below
'.Close SaveChanges:=True
End With
Else '<~~ Sheet Not Found'~~> Do What ever you want to do here when the sheet is not found
End If
Else
'~~> Do What ever you want to do here when the workbook is not found
End If
End Sub
'~~> Function to check if File exists
Public Function FileExists(strFullPath As String) As Boolean
On Error GoTo Whoa
If Not Dir(strFullPath, vbDirectory) = vbNullString _
Then FileFolderExists = True
Whoa:
On Error GoTo 0
End Function
'~~> Function to check if sheet exists
Function SheetExists(wst As String) As Boolean
Dim oSheet As Worksheet
On Error Resume Next
Set oSheet = Sheets(wst)
On Error GoTo 0
If Not oSheet Is Nothing Then SheetExists = True
End Function
HTH
Sid
Last edited by Siddharth Rout; Jan 17th, 2012 at 06:54 AM.
Reason: typo
A good exercise for the Heart is to bend down and help another up...
Please Mark your Thread "Resolved", if the query is solved
MyGear:
★ CPU ★ Ryzen 5 5800X
★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
★ Keyboard ★ TVS Electronics Gold Keyboard
★ Mouse ★ Logitech G502 Hero
koolsid that above code looks like it will work for my scenario. Thank you for providing it! The workbook to open and the fileName to saveAs I just left blank because I wasn't sure the exact location of where they were going to be housed. But thank you and westconn1 for pointing out that issue, sometimes it is the simplest things that cause code to fail.
Koolsid one question about your code you provided at the end of the module (I added two commented out lines with a question...
Code:
Public Sub Monthly(varStar)
Dim NewName As String
Dim Filefrmt As Long
'~~> New Name for the File (Will be required if you are doing a SAVE AS
NewName = "NewRain"
'~~> Check if the workbook exists
If FileExists(FilePath & FileName & FileExt) Then
'~~> If exists, open it
Set Wb = Workbooks.Open(FilePath & FileName & FileExt)
'~~> Check if Sheet exists
If SheetExists(varStar) Then
Run "RefreshOnOpen"
'~~> Comment the below 6 lines if you are not doing a SAVE AS
Select Case FileExt
Case ".xls": Filefrmt = 56
Case ".xlsx": Filefrmt = 51
Case ".xlsm": Filefrmt = 52
Case ".xlsb": Filefrmt = 50
End Select
With Wb
.SaveAs FilePath & NewName & FileExt, Filefrmt
.Close SaveChanges:=False
'--------------- NOTE ---------------
'~~> If you are just trying to save the existing file then you do not need a SaveAs
'~~> Comment the above two lines and uncomment the below
'.Close SaveChanges:=True
End With
Else '<~~ Sheet Not Found
'~~> Do What ever you want to do here when the sheet is not found
End If
Else
'~~> Do What ever you want to do here when the workbook is not found
'What I want to do here is if the workbook/worksheet is non existent then continue to cycle
'through the Array. Meaning that if Rain doesn't exist, it's okay, just move on to Sleet
'What would I need to put here to make it continue on to the next procedure if it's non-existent
End If
End Sub
Else
'~~> Do What ever you want to do here when the workbook is not found
'What I want to do here is if the workbook/worksheet is non existent then continue to cycle
'through the Array. Meaning that if Rain doesn't exist, it's okay, just move on to Sleet
'What would I need to put here to make it continue on to the next procedure if it's non-existent
A good exercise for the Heart is to bend down and help another up...
Please Mark your Thread "Resolved", if the query is solved
MyGear:
★ CPU ★ Ryzen 5 5800X
★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
★ Keyboard ★ TVS Electronics Gold Keyboard
★ Mouse ★ Logitech G502 Hero
I changed that line of code and it took away the compile error. But I am still running into the same issue I was having before. The code I posted is just a smaller portion of a larger project and it will open a workbook that contains about 500 worksheets, if the worksheet doesn't exist the code begins to spool the entire workbook for conversion to pdf! Maybe my coding error is in another portion of the code. I tried to upload a sample workbook, but it said it was an invalid format...so I am going to attach a txt file with my coding included to see if one of the guru's here can show me the error in my ways.
Searches the two strPathArr locations because the file is ALWAYS in one of the two locations (depending on the report it could be more than two tho) and will search both of the locations for the file. When the file is found it will open the file, Refresh the 2 queries inside of the file then save the file in the specified locatoin and with the specified name
Step_Two
Opens the specified workbook and searches each tab inside of the workbook for the worksheet named varBook, when varBook is found it will then copy that worksheet (varBook) to a new workbook then save in the specified location and with teh specified filename
Step_Three
Opens the specified file, then refreshes all the queries in the workbook, then saves the new file in the specified location and with the specified name.
Also, let me add (i hadn't updated my code yet) that in step 2, once the worksheet is copied to a new workbook, any highlighting that is on the sheet needs to be removed.
Could you test this code for me? This is only for Step one.
Code:
Option Explicit
Dim WB As Excel.Workbook
Public Sub Combine()
Dim varBook, varBooks
varBooks = Array("Fire", "Ice")
For Each varBook In varBooks
Call Step_One(varBook)
'Call Step_Two(varBook)
'Call Step_Three(varBook)
Next varBook
End Sub
Public Sub Step_One(varBook)
Dim varWorksheets, varWorksheet
Dim fileName1 As String, fileName2 As String, fileName3 As String
Dim sPath As String, FileToUse As String
Dim strPathArr(1 To 2) As String
Dim wks As Worksheet, qt As QueryTable
sPath = "C:\Reporting Folder\"
strPathArr(1) = sPath & varBook & "Review\"
strPathArr(2) = sPath & varBook & "To_Review\"
fileName1 = "_Monthly.xls"
fileName2 = "_Quarterly.xls"
fileName3 = "_Daily.xls"
varWorksheets = Array(fileName1, fileName2, fileName3)
For Each varWorksheet In varWorksheets
If FileExists(strPathArr(1) & "\" & varBook & varWorksheet) Then
FileToUse = strPathArr(1) & "\" & varBook & varWorksheet
ElseIf FileExists(strPathArr(2) & "\" & varBook & varWorksheet) Then
FileToUse = strPathArr(2) & "\" & varBook & varWorksheet
End If
If Len(Trim(FileToUse)) <> 0 Then
Set WB = Workbooks.Open(FileToUse)
For Each wks In WB.Worksheets
For Each qt In wks.QueryTables
qt.Refresh BackgroundQuery:=False
Next qt
Next wks
Set qt = Nothing
Set wks = Nothing
WB.SaveAs "Z:\Ready\" & VBA.Left(ActiveWorkbook.Name, _
VBA.InStrRev(WB.Name, ".") - 1) & "_" & VBA.Format(Date, "mmddyyyy") & ".xls", 56
WB.Close SaveChanges:=False
End If
Next varWorksheet
End Sub
'~~> Function to check if File exists
Public Function FileExists(strFullPath As String) As Boolean
On Error GoTo Whoa
If Not Dir(strFullPath, vbDirectory) = vbNullString _
Then FileExists = True
Whoa:
On Error GoTo 0
End Function
Last edited by Siddharth Rout; Jan 17th, 2012 at 12:22 PM.
Reason: Typo
A good exercise for the Heart is to bend down and help another up...
Please Mark your Thread "Resolved", if the query is solved
MyGear:
★ CPU ★ Ryzen 5 5800X
★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
★ Keyboard ★ TVS Electronics Gold Keyboard
★ Mouse ★ Logitech G502 Hero
I pasted the code into a new workbook just to make sure there wouldn't be any conflicts between variables etc etc from things I already had. The "FileFolderExists" I was getting the conflict on, was the FileFolderExists from the function
Code:
Public Function FileExists(strFullPath As String) As Boolean
On Error GoTo Whoa
If Not Dir(strFullPath, vbDirectory) = vbNullString _
Then FileFolderExists = True
Whoa:
On Error GoTo 0
End Function
But changing it to fileExists takes the compile error away so I will try that.
Hey, I didn't know that handy trick! The code begins to execute as expected, but now I get a debug error on the Method Save As Object 'Workbook failed.
Public Sub Step_Two(varBook)
Dim ws As Worksheet
If FileExists("c:\Main_Master.xls") Then
Set WB = Workbooks.Open(Filename:="c:\Main_Master.xls")
On Error Resume Next
Set ws = WB.Sheets(varBook)
On Error GoTo 0
If Not ws Is Nothing Then
ws.Copy
WB.SaveAs Filename:="Z:\Ready\" & ws.Name
End If
End If
End Sub
Edit: Remember to remove the Single Quote " ' " before Call Step_Two(varBook) in Sub Combine.
Last edited by Siddharth Rout; Jan 17th, 2012 at 01:00 PM.
Reason: Code updated
A good exercise for the Heart is to bend down and help another up...
Please Mark your Thread "Resolved", if the query is solved
MyGear:
★ CPU ★ Ryzen 5 5800X
★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
★ Keyboard ★ TVS Electronics Gold Keyboard
★ Mouse ★ Logitech G502 Hero
That code works as well. One tweak if possible, it's not closing the workbook. It is closing the workbook that we opened to copy the worksheet from, but it is not closing the workbook that we copied the single sheet into.
Public Sub Step_Two(varBook)
Dim ws As Worksheet
Dim wb2 As Workbook
If FileExists("c:\Main_Master.xls") Then
Set WB = Workbooks.Open(Filename:="c:\Main_Master.xls")
On Error Resume Next
Set ws = WB.Sheets(varBook)
On Error GoTo 0
If Not ws Is Nothing Then
ws.Copy
Set wb2 = ActiveWorkbook
wb2.SaveAs Filename:="Z:\Ready\" & ws.Name & ".xls"
wb2.Close SaveChanges:=False
WB.Close SaveChanges:=False
Set ws = Nothing
Set wb2 = Nothing
Set WB = Nothing
End If
End If
End Sub
Public Sub Step_Three(varBook)
If FileExists("C:\Ready\Daily\" & varBook & ".xls") Then
Set WB = Workbooks.Open(Filename:="C:\Ready\Daily\" & varBook & ".xls")
Run "RefreshOnOpen"
'~~> Replace NEWNAME with the name you want to save as
WB.SaveAs Filename:="Z:\Ready\" & "NEWNAME" & ".xls"
WB.Close SaveChanges:=False
Set WB = Nothing
End If
End Sub
A good exercise for the Heart is to bend down and help another up...
Please Mark your Thread "Resolved", if the query is solved
MyGear:
★ CPU ★ Ryzen 5 5800X
★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
★ Keyboard ★ TVS Electronics Gold Keyboard
★ Mouse ★ Logitech G502 Hero
It looks like I had left off some of the code. That is now working, however it looks like if the varBook does not exist in Step_One it automatically cycles to the next varBook as opposed to checking Step_Two/Step_Three for the varBOok