Re: Today() In Vba Code
OK It actually doesnt work. Datemin is empty. Function doesn't get called.
Apologies, looks like I still need help!
Re: Today() In Vba Code
OK It actually doesnt work. Datemin is empty. Function doesn't get called.
Apologies, looks like I still need help!
I have a calendar in my spreadsheet that returns a date selected to a cell that is active.
When the user clicks cell D40 in worksheet Surcharges, I use a Worksheet_SelectionChange event to show the calendar. When the user selects a date it returns the date in that cell.
Problem is I want to limit the user to select a date no more than 90 days from today's date.
I was having a problem using today() in the vba code.
When i enter todays date in cell E39 (-today()) and use the code below it works:
Private Sub Calendar1_Click()
ActiveCell.Value = Calendar1.Value
Unload Me
If Calendar1.Value - Range("e39").Value > 90 Then
MsgBox "over 90!"
Range("d40").Value = ""
Exit Sub
End If
End Sub
Display More
But when I try to use the today() function below I get errors:
Private Sub Calendar1_Click()
Dim x As Date
ActiveCell.Value = Calendar1.Value
Unload Me
x = date(today())
If Calendar1.Value - x > 90 Then
MsgBox "over 90!"
Range("d40").Value = ""
Exit Sub
End If
End Sub
Display More
What am I doing wrong? I would prefer to avoid putting =today() in a cell and refer to it. Is that even possible?
Re: Sort Worksheets By Name
Worked wonderfully! Just had to change the 6 to a 7
Sub sortsheets()
Dim lCount As Long, lCounted As Long
Dim lShtLast As Long
Dim lShtFirst As Long
lShtFirst = Sheets("Create Origin Zones").Index 'find sheet# of 'Create origin zones' to copy sheets after
lShtLast = Sheets("Surcharges").Index 'find sheet# of 'Create origin zones' to copy sheets after
For lCount = lShtFirst To lShtLast
For lCount2 = lCount To lShtLast
' If UCase(Sheets(lCount2).Name) < UCase(Sheets(lCount).Name) Then
If Val(Mid(Sheets(lCount2).Name, 7)) < Val(Mid(Sheets(lCount).Name, 7)) Then
Sheets(lCount2).Move Before:=Sheets(lCount)
End If
Next lCount2
Next lCount
End Sub
Display More
Quote from mikerickson
Re: Method Of Worksheet Class Failed
Thanks for the advice, I did look through the search with the new title. I kind of used an idea of one but put it inside an error handler instead of a seperate sub
Dim varTCMasterWorkbook
varTCMasterWorkbook = ActiveWorkbook.Name 'master workbook name
'loop through checkboxes, etc
Err.Clear
On Error Resume Next
Sheets("Shp Profile Tmpt").Copy after:=Sheets(shtnum) 'copy after 17th sheet
'error handler for 1004 problem
If Err <> 0 Then
Sheets("Create Origin Zones").OLEObjects(chknum).Object.Value = True 'recheck last button as it won't copy
Application.DisplayAlerts = False
MsgBox "Due to the large number or origins created, Excel will now" _
& Chr(13) & "save the workbook as " & varTCMasterWorkbook
'set desired settings, save and close the book
Sheets("Shp Profile Tmpt").Visible = False
Sheets("Create Origin Zones").Select
ActiveWorkbook.Save
obook.Close SaveChanges:=True
'open book
Set obook = Nothing
Set obook = Application.Workbooks.Open("C:\Tool\" & varTCMasterWorkbook)
Application.DisplayAlerts = True
Exit Sub
End If
On Error GoTo 0
Display More
Quote from Dave HawleyThere are other ways! Which is why I edited your title so you can find them.
Re: Sort Order Of Worksheets By Name
The 17 sheets at the beginning all have unique names, none of which contain text 'Origin'.
The sheets that follow the 'Origin' sheets being inputted also have unique names and are unhidden after the macro creates these origin sheets.
Do you want me to explicitly write down the 17 sheet names? The sheet 'Create Origin Zones' is the one that will always be before the first Origin sheet, if that helps?
Quote from rbrhodesHi MrF,
What's the name of the other sheets? In other words do you need a custom sort?
[hr]*[/hr] Auto Merged Post;[dl]*[/dl]Thanks for the link. I applied the code to my workbook, except the sorting isn't perfect.
It will sort Origin 49, then Origin 5, then Origin 50 (since I do not have 0's in my single digit origins)
Sub sortsheets()
Dim lCount As Long, lCounted As Long
Dim lShtLast As Long
Dim lShtFirst As Long
lShtFirst = Sheets("Create Origin Zones").Index 'find sheet# of 'Create origin zones' to copy sheets after
lShtLast = Sheets("Surcharges").Index 'find sheet# of 'Surcharges' to stop the sort below
For lCount = lShtFirst To lShtLast
For lCount2 = lCount To lShtLast
If UCase(Sheets(lCount2).Name) < UCase(Sheets(lCount).Name) Then
Sheets(lCount2).Move Before:=Sheets(lCount)
End If
Next lCount2
Next lCount
End Sub
Display More
Quote from Will Riley
I have a workbook with MANY worksheets.
The first 17 are static, as well as the 18th sheet on to the end,but there can be many sheets added in between sheets 17 and 18 (up to 56 added) all named Origin 1, Origin 2....Origin 56.
Users can add these sheets in any order as many times as they want, but eventually the order of the sheets will not be in ascending order.
I wanted to know how to organize the sheets in order of Origin 1, Origin 2, Origin 3, etc after the user adds new sheets with the macro.
I can find out how to add it to my current module on my own.
Thanks
Re: Method Of Worksheet Class Failed
As I state in my question:
"All the solutions I saw involve saving, closing and reopening the workbook but this interrupts my loop. (It would save my workbook and close it.)"
Quote from Dave HawleyThe same question has been asked and answered many times. See your Answers above.
I have a worksheet "Create Origin Zones" - sheet #17 in the array - that has 56 checkboxes.
Users can click anywhere from 1 to 56 checkboxes, and for each checkbox that is checked, I unhide a sheet "Shp Profile Tmpt", copy it after sheet #17, rename it to "Origin " + checkbox#, and give it a title based on a variable in another sheet.
Once that loop is done, I then hide the "Create Origin Zones" sheet, but the user can click a button on the new sheet to go back to the 'Create Origin Zones" sheet and add more zones by clicking more checkboxes and re-running the macro.
Problem is I get that "Run-time error '1004':Copy Method of Worksheet Class failed" when I copy too many sheets. All the solutions I saw involve saving, closing and reopening the workbook but this interrupts my loop. (It would save my workbook and close it.)
I am trying to have somewhere in my loop, say every time 20 or more checkboxes are checked, its saves, closes, reopens and continues the loop to the next checkbox and repeats the copy and paste and renaming etc.
Below is my code:
Sub pick_origin()
chkcounter = 0
shtnum = Sheets("Create Origin Zones").Index 'find sheet# of 'Create origin zones' to copy sheets after
For i = 1 To 56 'for the 56 origin zones checkboxes
chknum = "CheckBox" + Trim((Str(i))) 'variable used for CheckBox #s
title = Sheets("Create Origin Zones").Range("O" + Trim((Str(i)))) 'variable used for range of description (cell O1-O56)
orgnum = "Origin " + Trim((Str(i))) 'variable used for renaming sheets
If Sheets("Create Origin Zones").OLEObjects(chknum).Object.Value = True Then 'if checked
chkcounter = chkcounter + 1
Sheets("Shp Profile Tmpt").Visible = True 'make appear
Sheets("Shp Profile Tmpt").Select 'give focus
Err.Clear
On Error Resume Next
Sheets("Shp Profile Tmpt").Copy after:=Sheets(shtnum) 'copy after 17th sheet
On Error GoTo 0
shtnum = shtnum + 1 'add to counter to add to right of next sheet
Sheets("Shp Profile Tmpt (2)").Select
Range("H1").Value = orgnum + " - " + title 'insert title
Range("Z1").Value = i 'insert origin number
Range("H1").Select
'***Since we're naming the sheets here, deal with the dupes here***
Err.Clear
On Error Resume Next
Sheets("Shp Profile Tmpt (2)").Name = orgnum 'rename sheet
If Err <> 0 Then
Application.DisplayAlerts = False
Sheets("Shp Profile Tmpt (2)").Delete
Application.DisplayAlerts = True
Else
Sheets("Shp Profile Tmpt (2)").Name = orgnum 'rename sheet
End If
On Error GoTo 0
Sheets("Shp Profile Tmpt").Visible = False 'hide original sheet
End If
Sheets("Shp Profile Tmpt").Visible = False
Next
Sheets("Create Origin Zones").Select
If chkcounter = 0 Then
MsgBox "Please check off at least one origin zone", , "Missing Information"
Range("d26").Select
Exit Sub
Else
MsgBox "Your origin zones have been created." _
& Chr(13) & "Please fill in shipment information for each origin zone created," _
& Chr(13) & "as well as surcharge and product discounts", , "Information"
If Sheets(shtnum + 1).Name = "Surcharges" Then
Sheets("Create Origin Zones").Visible = True
Sheets(shtnum).Select
Else
Sheets("Create Origin Zones").Visible = False
Sheets(shtnum + 1).Select
End If
End If
For cb = 1 To 56 'for the 56 origin zones
chknumm = "CheckBox" + Trim((Str(cb))) 'variable used for CheckBox #s
Sheets("Create Origin Zones").OLEObjects(chknumm).Object.Value = False
Next
Application.EnableEvents = True
Sheets("Create Origin Zones").OLEObjects("OptionButton2").Object.Value = True
Exit Sub
Sheets("Surcharges").Visible = True
Sheets("Express 9AM").Visible = True
Sheets("Express 1030AM").Visible = True
Sheets("Express").Visible = True
Sheets("Ground").Visible = True
Sheets("Express_US").Visible = True
Sheets("Ground_US").Visible = True
Sheets("Express_International").Visible = True
End Sub
Display More
Re: Drop Down Cell Link Reference
It sure does! Thank you so much!
Quote from Sicarii
I have 6 worksheets that are identical cosmetically. Each has the same drop down box list with the same name (dropdown1), however the cell link on each sheet is different. (ie. sheet1 dropdown1 cell link refers to a sheet 'lookup' cell $K$1, sheet2 dropdown1 cell link refers to sheet 'lookup' cell $K$2, etc.)
I have the same command button in each sheet that performs the same task so I wanted to keep one module for all 6. Problem is I set a variable to the cell link in the code, and this has to be changed.
Is there any way I can set this variable using a property of the drop down list?
ie
I don't want to create 5 more duplicate modules just to change this one bit of code (I only use it this time in the code!).
If there is no way to get the cell link value of the drop down, could I possibly put a worksheet change event on the lookup sheet to populate a certain static cell with the value of the last cell change?
Re: Copy Data From Hidden Worksheets
Ok I kind of get the copy way with hidden sheets, but my macro is a bit more complicated than a simply copy.
It takes a value in sheet1 and does a find for that value in sheet2.
Once it finds that value, it moves 10 left from the cell in sheet2 and copies that value back into a certain cell in sheet1.
How can I code the find function to look at a certain sheet?:
Set rcode = Cells.Find(What:=code_find, after:=ActiveCell, LookIn:=xlValues _
, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False)
[hr]*[/hr] Auto Merged Post;[dl]*[/dl]I have attached the sheets I am referring to. ( I still have to attach 1 more small sheet)
I removed a lot of things to keep the sizes within forum limits (the drop down for you only has 1 option, but there can be over 100!). You will have to merge the 3 sheets into 1 book for the code to work.
Also, the example in the drop down I selected uses the most lookups. My logic goes that if the row is 7 in sheet 1 and it finds a value in sheet 2, that value will be replicated for the remainder of the column. (so you will find an IF row = 7 in the coding that you can ignore for now)
Quote from Dave HawleyTo copy from a hidden Worksheet, use the Copy Method below. Both Sheets can be hidden and the names are CodeNames
[hr]*[/hr] Auto Merged Post;[dl]*[/dl]Last sheet to use
Quote from Dave HawleyTo copy from a hidden Worksheet, use the Copy Method below. Both Sheets can be hidden and the names are CodeNames
I have a macro that is grabbing up to 2,400 values from a hidden worksheet. Right now I have the worksheet being visible in order to get the values and paste them into the worksheet the user is on. It seems if I don't make the worksheet visible I get a select method error. I don't want the user to see 2 worksheet screens jumping back and forth like crazy for 20 seconds!
Below is a snip of my code.Please help!
shtnum = ActiveSheet.Name
chkcol = r + 3 'ADDED********
lookcol = r + 23
Sheets(shtnum).Range("A1").Select
ActiveCell.Offset(0, lookcol).Select 'this is for the column of the lookup
startletter3 = ColumnLetter2(ActiveCell.Column) 'returns letter of column
Sheets(shtnum).Range("A1").Select
ActiveCell.Offset(0, chkcol).Select 'this is for the column of the return value
startletter2 = ColumnLetter2(ActiveCell.Column)
retrow = 5
ret2row = 8
delrow = 7
For iWS = 1 To Worksheets.count
If Worksheets(iWS).Name = ReturnValue Then
Sheets(shtnum).Unprotect
For retrow = 5 To retend
sfound = sfound + 1
code_find = Sheets(shtnum).Range(startletter3 + Trim(Str(retrow))).Value
Worksheets(iWS).Visible = True
Worksheets(iWS).Select
Set rcode = Cells.Find(What:=code_find, after:=ActiveCell, LookIn:=xlValues _
, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False)
If Not rcode Is Nothing Then
rcode.Offset(0, -10).Select
code_disc = ActiveCell.Value
Sheets(shtnum).Range(startletter2 + Trim(Str(retrow))).Value = code_disc
Display More
Re: Worksheet Change Event
Wow I would have never gotten that! I closed and reopened, events are running again. Thanks so much! (I was wondering why nothing was happening!)
Quote from Bill RockenbachIf EnableEvents was shutoff and not turned back by on your code then the Excel Application (all open workbooks and sheets) will not respond to any Event. You either have to enable events with code or quite Excel and then reopen Excel.
I have a spreadsheet with a table of values in range E5 to T158.
A macro populates the table by looking up values on other sheets in the book. If the macro finds a value in the lookup for Row 7 of any column (ie E7,F7...T7) it populates the rest of the column with that value (E7 value gets pasted to E8:E158) THEN it protects the cells it pasted (E8:E158).
If the macro does NOT find a value for row 7, it simply skips it, leaving it blank, and continues to row 8 until it reaches row 158 of each column E to T.
I want to give the user flexibility with these values. So if the user either deletes E7 or changes the value of the contents in E7, I want to unprotect the cells of rows 8 to 158 for that column.
I have created a
in the private module for that sheet below. I thought it was working but it isn't doing anything when I change or delete the value in Cell E7 for example. Please help!
Private Sub Worksheet_Change(ByVal Target As Range)
'Do nothing if more than one cell is changed
If Target.Cells.count > 1 Then Exit Sub 'Or IsEmpty(Target)
If Not Intersect(Target, Range("E7:T7")) Is Nothing Then
'Ensure target is a number before multiplying by 2
If IsEmpty(Target) Then
'Stop any possible runtime errors and halting code
On Error Resume Next
'Turn off ALL events
Application.EnableEvents = False
ActiveSheet.Unprotect
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Target.Offset(0, -1).Select
'Range("E7").Select
'Turn events back on
Application.EnableEvents = True
'Allow run time errors again
On Error GoTo 0
End If
If Target.Value <> Target.Offset(0, 1).Value Then
On Error Resume Next
Application.EnableEvents = False
ActiveSheet.Unprotect
Target.Copy
Target.Offset(0, 1).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveCell.Offset(0, -1).Select
ActiveSheet.Protect
End If
End If
End Sub
Display More
Re: Get Worksheet Number
Thanks that helped a lot. I had to adjust the code slightly as if all the variable sheets were deleted (meaning Create Origin Zones would be 15 and Surcharges 16) I would want to unhide the Create Origin Zone sheets and give it focus. I couldnt just use
incase the user wanted to delete the first variable sheet but had a couple more after.
Dim j As Integer
With ActiveSheet
j = .Index - 1
Application.DisplayAlerts = False
.Delete 'deletes current variable sheet
Application.DisplayAlerts = True
End With
If Sheets(j).Name = "Create Origin Zones" And Sheets(16).Name = "Surcharges" Then 'if the user deletes the first variable sheet and there are no other variable cells to the right
Sheets("Create Origin Zones").Visible = True
Sheets("Create Origin Zones").Select
Else
Sheets(j+1).Select
Sheets("Create Origin Zones").Visible = False
End If
Display More
Quote from DerkDisplay MoreIf you are deleting the sheet with a macro, then you can get it's index and use something like
[vba] Dim j As Integer
With Sheets("SheetToDelete")
j = .Index - 1
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
End With
Sheets(j).Select[/vba]
Re: Get Worksheet Number
as previously stated the sheets i create have variable names so i cannot select a sheet by name.
ie a macro creates 3 sheets inbetween Create Origin Zones and Surcharges. Each of these sheets is a copy of a template in the workbook, and they each have a button to execute the macro I posted above. Say for instance I delete the 2nd variable worksheet, I want the focus to go on the first variable worksheet, or if I delete the 3rd I want focus on the 2nd one. Really the user can create up to 56 sheets in between Create Origin Zones and Surcharges so I prefer that the user gets focus of the sheet before the one they just deleted instead of going to Create Origin Zones or the first variable sheet
Quote from norieWhy are you using the sheet index?
I have a macro that is creating and deleting variable worksheets. Right now when it deletes the sheet, I have it going to focus on the 16th sheet.
What I want to do is move the active sheet one before (to the left) of the sheet I just deleted.
Here is what I have below. Sheet "Create Origin Zones" is the 15th sheet...Sheet"Surcharges" is the 16th sheet, but the variable sheets get created in between these sheets, so the "Surcharges" array number changes from 16.
Sub delete_origin()
Application.DisplayAlerts = False
ActiveWorkbook.ActiveSheet.Delete
If Sheets(16).Name = "Surcharges" Then 'this means all the variable sheets have been deleted
Sheets("Create Origin Zones").Visible = True 'we want to show the sheet that creates variable sheets
Sheets("Create Origin Zones").Select
Else
Sheets("Surcharges").Select
Sheets("Create Origin Zones").Visible = False
Sheets(16).Select 'set focus to first variable sheet
End If
Application.DisplayAlerts = True
End Sub
Display More
Re: Close Certain Workbook With Vba
Some great tips thanks...but I am getting an error when I try to create the email
is highlighted
error msg is: Run-time error 429. ActiveX component can't create the object
this didnt happen yesterday. how do i fix that? thanks
Quote from Dave HawleyThis should get you there;
I have a macro that copies 2 worksheets of an open workbook "Combined Sales Tool" and saves those 2 sheets in the root of the C drive with a variable name.
I want to know how I can #1 close the newly created workbook, #2 focus back to the original workbook "Combined Sales Tool", hide the 2 sheets that were copied to the new file, then close the original workbook with (and for example without) saving
Thanks!
part of my code below:
Sub esummary()
Dim OutApp4 As Object
Dim OutMail4 As Object
Dim cell As Range
Dim filedoc As String
Dim intFreeRow
Dim emailatt4 As String
Sheets("Summary").Visible = True
Sheets("Email").Visible = True
Sheets(Array("Summary", "Email")).Select
Sheets("Summary").Activate
Sheets(Array("Summary", "Email")).Copy
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.CutCopyMode = False
Sheets("Email").Select
Cells.Select
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Summary").Select
Sheets("Summary").Activate
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
Sheets("Email").Select
Range("B3").Select
If Not flExists("C:\" & RTrim(ActiveCell.Value) & ".xls") Then
ChDir "C:\"
ActiveWorkbook.SaveAs filename:= _
"C:\" & RTrim(ActiveCell.Value), FileFormat:= _
xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
Else
MsgBox "The file" & RTrim(ActiveCell.Value) & ".xls already exists. Please delete old file or rename Company"
Exit Sub
End If
'email here
emailatt4 = "C:\" & RTrim(Sheets("Email").Range("b3")) & ".xls"
Worksheets("Email").Range("A1").Select
Application.ScreenUpdating = False
Set OutApp4 = CreateObject("Outlook.Application")
OutApp4.Session.Logon
Set OutMail4 = OutApp4.CreateItem(0)
With OutMail4
.To = ActiveCell.Value
.CC = ActiveCell.Offset(1, 0)
.Subject = ActiveCell.Offset(2, 0)
.Body = ActiveCell.Offset(3, 0) & vbCrLf & vbCrLf
.Body = .Body & ActiveCell.Offset(4, 0) & vbCrLf & vbCrLf
.Body = .Body & ActiveCell.Offset(5, 0) & vbCrLf & vbCrLf
If Not (Len(Dir(emailatt4)) > 0) Then
MsgBox "The file " & emailatt4 & ".xls cannot be found. Please save to C:\", vbOKOnly
Sheets("Email").Select
ActiveWindow.SelectedSheets.Visible = False
Exit Sub
Else
.Attachments.Add emailatt4
End If
.display
End With
Sheets("Email").Select
ActiveWindow.SelectedSheets.Visible = False
ThisWorkbook.Save
End Sub
Display More