VBA Excel End If without block If Error - vba

I have a lite problem with some statement in my code. the situation is like this:
I am working with UserForm in excel based on selection of months and the data goes to my report from another report. To analyze data of certain month we need data of the month before. So for January we need data from last's year database for December.
I made special sub just in case we need to analyze data about January and we need the old database too. And with that statment I have a problem and I get that error "VBA End If without block If Error" :
'If the month that was selected is January then we need to open old Visual file Month
If MonthName = Lists.Range("A2").Value Then 'it means January
Call January
Else
For Each ws In Worksheets
If ws.Name = "December" Then
Sheets("December").Delete
End
End If
Next ws
End If
Please, can someone help?

Use Exit For to exit a For Loop.
If MonthName = Lists.Range("A2").Value Then 'it means January
Call January
Else
For Each ws In Worksheets
If ws.Name = "December" Then
ws.Delete
Exit For
End If
Next ws
End If

Related

Variable Range VBA Using Months

I am trying to create a variable range that will update and bring in a different range of values based on what month it is.
January C8:D8
February C9:D9
March C10:D10
April C11:D11
May C12:D12
June C13:D13
July C14:D14
August C15:D15
September C16:D16
October C17:D17
November C18:D18
December C19:D19
These are the ranges I need based on what month it is.
My Existing Code:
Sub PullDataFromClosedWorkbook()
Dim Source As Workbook
Set Source = Workbooks.Open("H:\Integration Projects\Chk Req & Customer
Payment Sheet\Chk Reqs\Check Request.xlsm", True, True)
'bring to this workbook
ThisWorkbook.Activate
Worksheets("Sheet1").Range("B2:C2").Formula = Source.Worksheets("Consolidated
Summary").Range("C11:D11").Copy
Worksheets("Sheet1").Range("B2:C2").PasteSpecial xlPasteValues
Source.Close SaveChanges:=False
End Sub
My first idea was to create an if function that based on a drop down list with the months in it, that it could vlookup the month and set the range to that. Not sure how to do this in vba.
One way to do this would be to use the Month Function to return the current month number, which you can then use as an Offset from a starting range.
For example, since it's August, Month(Date) returns 8. If your starting range is C7:D7, Range("C7:D7").Offset(Month(Date)) refers to C15:D15.
So your code might look something like this (UNTESTED).
Sub PullDataFromClosedWorkbook()
Dim Source As Workbook
Set Source = Workbooks.Open("H:\Integration Projects\Chk Req & Customer Payment Sheet\Chk Reqs\Check Request.xlsm", True, True)
ThisWorkbook.Worksheets("Sheet1").Range("B2:C2").Value = Source.Worksheets("Consolidated Summary").Range("C7:D7").Offset(Month(Date)).Value
Source.Close SaveChanges:=False
End Sub

Opening a new worksheet with the NEXT date

so I need a macro code for naming a worksheet with the next date on it, as in if the previous sheet is called Tue 27 then the next sheet (new one) should be Wed 28,
my current code only names it as TODAYS date, this is what I am using
Dim szTodayDate As String
szTodayDate = Format(Date, "ddd") & Format(Date, " dd")
On Error GoTo MakeSheet
Sheets(szTodayDate).Activate
Exit Sub
MakeSheet:
Dim Srt As Worksheet
Set Srt = ActiveSheet
Sheets.Add
ActiveSheet.Name = szTodayDate
Is it even possible to do this, and if so, can anyone please tell me how,
Thank you
additional note: so the macro creates a new sheet everytime I run it, and then names it with todays date, I need it instead to name it with the NEXT date, in relation to the previous sheet. so if the last sheet made (prior to macro run) is called "Sun 02" the macro should create a sheet and name it "Mon 03", assume for now that the month doesn't matter, I will not run this macro after the month ends, so on workbook Feb, "Wed 28" would be the last time I run this macro.
Reason Explained: so I need to create a new worksheet everyday for work, but I sometimes end up having to make the worksheet a day later, so lets say on sun 02 I make the sheet on time, so now I have worksheet sun 02, but then I miss it on monday, then on tuesday I make the sheet, it ends up making Sheet Tue 04, so now I'm missing Mon 03.
Possible Alternate: If I could somehow set an IF function that can check to see if worksheet with yesterdays name exists (maybe going back upto 2 days) and if not create it, that would work to. but not sure how to code said IF function either (It would also need to create it and name it as today, if today is 01).
Thank you again
An important note for the following code: in its default state it requires that the Sheet Names include the Month, so the format is "ddd dd mmm" ("Wed 28 Feb") not "ddd dd" ("Wed 28"). If, for example, the Month is stored in the FileName instead then you will need to modify the code.
We need a variable to store the most recent date found, and a Worksheet object to use in a For Each loop. We will check each Worksheet's Name and check if it IsDate. If it is, then we will see if it is later than our currently stored Date. This will fail at year end, unless you start including the Year in the Sheet Name (or File Name) too. (Since 1 Jan comes before 31 Dec)
Dim dMaxDate AS Date, wsForLoop AS Worksheet, sTestString AS String
dMaxDate = DateSerial(1900,1,0) 'Default to 0
For Each wsForLoop In ThisWorkbook.Worksheets 'Loop through every worksheet
sTestString = wsForLoop.Name 'Get the name of the sheet
If InStr(sTestString, " ") > 0 Then sTestString = Mid(sTestString, 1+InStr(sTestString, " ")) 'Remove the Weekday
'If you need to add the Month/Year from your filename, do that here
If IsDate(sTestString) Then 'Only check Worksheets with Dates for Names
If cDate(sTestString) > dMaxDate Then dMaxDate = cDate(sTestString) 'If this is a later date then store it
End If
Next wsForLoop 'Return to start of loop
If dMaxDate < DateSerial(1900, 1, 1) Then dMaxDate = Now-1 'If we have no Worksheets with Dates for Names then default to yesterday
With ThisWorkbook.Worksheets.Add 'Add a new sheet
'Change the Format if you are adding the Month and/or Year from Filename
.Name = Format(dMaxDate+1, "ddd d mmm") 'And Name it the day after our stored date
End With
try using below, you can use counter instead of 1.
SZTodayDate = Format(Date + 1, "ddd") & Format(Date + 1, " dd")

Looking for a custom solution to copy data from one workbook to another

I am trying to simplify a process for field employees at my work. The baseline case is that the employees fill out Daily Detail Reports in a single Excel Workbook throughout the year with the hours they have worked that day, the project # and Phase Code their labor costs will hit and the hours that they worked that day on that particular project. It is very common for the same project number and phase code to be used more than once for a single day (i.e. multiple row entries which will need the total hours added together based on the condition of having the same project number and phase code for that day). See attached "Detail Report WB" image.
Our employees then have to enter the same data in a different format (i.e. only one line allowed per project number and phase code pair per day) in a separate workbook. See attached "Timesheet Import WB" image. The timesheet workbook is driven based on the week end date for that week (i.e. Sunday). The Daily Detail Report workbook however, is driven based on the week beginning date and Sundays are not included in the Daily Detail Report. To make things more complicated, the dates listed in the Daily Detail report are based on formulas and do not house the actual date value in the cells.
The goal of this solution is to take the information entered into the Daily Detail Report workbook and place it into the Timesheet workbook via a sub function based on a ActiveX command button click event. See the attached “End Goal” image.
So far I have compiled the following code to allow the user to click the import button which prompts the user to find the Daily Detail Report workbook that they would like to import data from. This code also allows for the user to input the week end date desired for the Timesheet workbook. I was trying to use the week end date to find the desired data in the Daily Detail Report workbook, but this is proving difficult. Any assistance would be greatly appreciated. It’s been years since I took into to computer programming in VBA back in college.
Images are located here: https://drive.google.com/drive/folders/0B7BjXxM59FFyQlM5eThvc0dDWUU?usp=sharing
Thanks!
Private Sub CommandButton1_Click()
'Define All Variables
Dim GCell As Range
Dim fDialog As FileDialog, result As Integer
Dim MyDetailReport As String
Dim MyTimeSheet As String
Dim MySheet As String
Dim ProjNum As String
Dim PhaseCode As String
Dim Hours As String
Dim WkEndDate As String
'Find source file
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
fDialog.AllowMultiSelect = False
fDialog.Title = "Select Daily Report File to Import"
fDialog.InitialFileName = "W:\PDX - Mechanical Construction\Operations\Detailing\Daily Tracking Logs\"
fDialog.Filters.Clear
fDialog.Filters.Add "Excel files", "*.xlsx"
If fDialog.Show = -1 Then
MyDetailReport = fDialog.SelectedItems(1)
End If
'Enter date to look for in workbook
WkEndDate = InputBox("Insert Week End Date in format mm/dd/yyyy", "User date", Format(Now(), "mm/dd/yyyy"))
If IsDate(WkEndDate) Then
WkEndDate = Format(CDate(WkEndDate), "mm/dd/yyyy")
'Place Week End Date into Timesheet workbook
With ThisWorkbook.ActiveSheet.Range("AE5")
.Value = WkEndDate
End With
Else
MsgBox "Wrong date format"
End If
'Use the current sheet to store found data
MySheet = ActiveSheet.Name
'Use Error Handling routine in case of errors
On Error GoTo ErrorHandler
'Turn off screen updating to run macro faster
Application.ScreenUpdating = False
Workbooks.Open Filename:=MyDetailReport & MyTimeSheet
'Search Detail Report "Daily Report Log" sheet for the selected Week End Date
Set GCell = ActiveSheet.Cells.Find(WkEndDate, LookIn:=xlValues)
GCell = GCell.Offset(2, 1)
If GCell.Value = "" Then
GCell = GCell.Offset(1, 0)
Else
'copy data formulas to correct format for Timesheet workbook
End If
'Error Handling
ErrorHandler:
Select Case Err.Number
'Common error #2: the specified data wasn't in the target workbook.
Case 9, 91
Application.ScreenUpdating = True
MsgBox "The value " & WkEndDate & " was not found."
Exit Sub
'General case: turn screenupdating back on, and exit.
Case Else
Application.ScreenUpdating = True
Exit Sub
End Select
End Sub

Excel 2010 VBA to copy tab names to consecutive columns

I am trying to build quite a complex excel macro based on dynamic data. My first stumbling block is that i am struggling to get a button-triggered Excel macro to take name of each tab after the current one and insert its name every third column of the current sheet
I have:
Sub Macro1()
On Error Resume Next
For Each s In ActiveWorkbook.Worksheets
Sheet2.Range("A1:ZZ1").Value = s.Name
Next s
End Sub
This really does not work well, as it simply seems to enter the name of the last sheet all the way between A1 and ZZ1! what am I doing wrong?
This will put the names of worksheets in the tabs to the right of the Activesheet in every 3rd column of row 1 of the Activeshseet:
Sub Macro1()
Dim i As Long
With ThisWorkbook
'exit if Activesheet is the last tab
If .ActiveSheet.Index + 1 > .Worksheets.Count Then
Exit Sub
End If
For i = .ActiveSheet.Index + 1 To .Worksheets.Count
.ActiveSheet.Cells(1, (i - .ActiveSheet.Index) + (((i - .ActiveSheet.Index) - 1) * 2)) = .Worksheets(i).Name
Next i
End With
End Sub
Please note that it's a bad idea to useOn Error Resume Next in the general manner that you did in your original code. It can mistakenly mask other errors that you don't expect. It should just be used to catch errors that you do expect.

Excel 2003 VBA - Locate Date & Move Relevant data

I need to automate a process that's not a one-off event, ~500 facilities, each with 100+ assets which are all scheduled for different dates throughout the year for completion. I have a Workbook set up with my main/source sheet as well as 12 month sheets (Jan, Feb, March, ... Dec). What I need is some sort of code that would allow me to search for a particular date and send it as well as other same-row corresponding data to the appropriate sheet.
For example I have an asset that is due for maintenance in June, 6/17/11. I need for Excel to search for it using the month only, and moving that asset as well as it's name, description, cost, etc to the June tab. Ive managed to get it to locate assets searching for "6/" however it cannot find assets with a date of 6/17/11. It copies all needed data and attempts to move it to the proper sheet, when it makes this attempt a Microsoft Visual Basic error code 400 pops up. Any ideas? All help appreciated.
see if this helps ...
Private Sub FindCells()
'' step 1, find all the rows containing your date (June 2011 dates hardcoded in this example)
Dim CollectionOfRowRanges As New Collection
Dim ws As Worksheet
Dim rgCell As Range
For Each ws In ThisWorkbook.Worksheets
For Each rgCell In ws.UsedRange.Cells
If IsDate(rgCell.Text) Then
If Month(CDate(rgCell.Value)) = 6 And Year(CDate(rgCell.Value)) = 2011 Then
'' for debugging only ... watch and make sure it stops at the right places
ws.Activate
rgCell.Select
Stop
'' end of debug code
Call CollectionOfRowRanges.Add(rgCell.EntireRow)
End If
End If
Next rgCell
Next ws
'' step 2, copy the rows to a new wb
Set ws = Workbooks.Add.Sheets(1)
ws.Name = "June 2011 Rows"
Dim rgRow As Range
Set rgCell = ws.Cells(1, 1)
For Each rgRow In CollectionOfRowRanges
Call rgRow.Copy
Call rgCell.EntireRow.PasteSpecial(xlPasteValues)
Set rgCell = rgCell.Offset(1)
Next rgRow
End Sub