Access 2013: How to control what form changes get saved and which get cancelled - forms

I have a form with 3 buttons:
Save - which saves the form
NewReport - which becomes visible only after current form is saved and is supposed to clear the form and let the user input another form of data.
Close - which should close the application without saving the unfinished form.
I cannot seem to figure out how to control these functions using the Before Update event procedure.
One of the things that I do not understand is that the Save command doesn't actually wright the data to the table until I somehow change the focus of the form. So if my user is entering data and hits the Save button, at the completion of the save command, the table does not yet have the data saved. It only appears in the table after focus changes; like from a Requery.
Here is my code in its current version:
Option Compare Database
Option Explicit
Private Cause As Variant
Private Sub btnClose_Click()
Cause = "CloseButton"
DoCmd.Close acForm, "frmReports", acSaveNo
End Sub
Private Sub btnNewReport_Click()
Cause = "NewReport"
Me.Requery
Me.RepStatus = ""
End Sub
Private Sub cmdSave_Click()
Dim outl As Outlook.Application
Dim mi As Outlook.MailItem
'blnGood = True
Cause = "SaveButton"
'Save the Record
DoCmd.Save acForm, "frmReports"
' If Me.DateOfVisit <> "" Then
Me.RepStatus = "Report Saved!"
' Set outl = New Outlook.Application
' Set mi = outl.CreateItem(olMailItem)
' mi.Body = "A new report was just recorded."
' mi.Subject = Application.CurrentUser & " Just Logged a Report."
' mi.To = "rich.temen#cox.net"
' mi.Send
'
' Set mi = Nothing
' Set outl = Nothing
' End If
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strMsg As String
Select Case Cause
Case "SaveButton"
Me.btnNewReport.Visible = True
'do nothing
Case "NewReport"
'di this
Case "CloseButton"
Me.Undo
End Select
'If Not blnGood Then
' strMsg = "Please use the Save button to save your Report," & _
' vbNewLine & "or Escape to reset the form."
' Call MsgBox(Prompt:=strMsg, Title:="Before Update")
'End If
End Sub
Private Sub Form_Load()
Me.btnNewReport.Visible = False
Cause = ""
End Sub
Thanks for any help on this one, I have been going around in circles for hours.
Rich

Related

MS Access Apply Filter From Another Form

I have this code from another website but it's not working.
I want to filter the split view form from another form.
Private Sub btnSearch_Click()
'//Check that other form is loaded - if not, then open it
If Not fIsLoaded("frmMain") Then
DoCmd.OpenForm ("frmMain")
End If
'//Set filter to listbox criterion
Forms("frmMain").Filter = "[Priorities] = " & Chr(34) & Me.Priorities & Chr(34)
Forms("frmMain").FilterOn = True
End Sub
Function fIsLoaded(ByVal strFormname As String) As Boolean
'Returns False if form is not open or True if Open
If SysCmd(acSysCmdGetObjectState, acForm, strFormname) <> 0 Then
If Forms(strFormname).CurrentView <> 0 Then
fIsLoaded = True
End If
End If
End Function
I received this error
My best guess is the form wasn't ready to take a filter yet, and that's why the error occurred. DoCmd.OpenForm takes a Where argument to set the filter when opening to prevent this from occuring.
Private Sub btnSearch_Click()
'//Check that other form is loaded - if not, then open it with the filter
If Not fIsLoaded("frmMain") Then
DoCmd.OpenForm ("frmMain",,,"[Priorities] = " & Chr(34) & Me.Priorities & Chr(34))
Else
'//Set filter to listbox criterion
Forms("frmMain").Filter = "[Priorities] = " & Chr(34) & Me.Priorities & Chr(34)
Forms("frmMain").FilterOn = True
End If
End Sub
Check if this works. If not, your filter might not be valid for that form.

Excel values to PDF form fields

objJSO.GetField(strField).Value = (strFieldVal) - That is the line I'm recieving a 'type mismatch' error on.
I've found the code base from "My Engineering World". It is an old post.
I'm selecting a static PDF form and trying to write values from an excel doc to the PDF form which contains the same field names. The excel doc has the field names in column c20-149 with the values for those fields in d20-149. I'm trying to write the values for those fields into the selected PDF form.
Option Explicit
Sub btnToPDF_Click()
Dim objAcroApp As Object
Dim objAcroAVDoc As Object
Dim objAcroPDDoc As Object
Dim objJSO As Object
Dim fd As Office.FileDialog
Dim strFile As String
Dim strField As String
Dim strFieldVal As String 'Used to hold the field value
Dim r As Long 'Used to increase row number for strfield name
'Disable screen flickering.
Application.ScreenUpdating = False
'Choose the Onsite Survey form you want to fill
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the On-site survey PDF."
.Filters.Clear
.Filters.Add "PDF", "*.PDF"
'.Filters.Add "All Files", "*.*"
'If the .Show method returns False, the user clicked Cancel.
If .Show = True Then
strFile = .SelectedItems(1)
MsgBox (strFile)
End If
End With
'Initialize Acrobat by creating the App object.
Set objAcroApp = CreateObject("AcroExch.App")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "Could not create the App object!", vbCritical, "Object error"
'Release the object and exit.
Set objAcroApp = Nothing
Exit Sub
End If
'Create the AVDoc object.
Set objAcroAVDoc = CreateObject("AcroExch.AVDoc")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "Could not create the AVDoc object!", vbCritical, "Object error"
'Release the objects and exit.
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
Exit Sub
End If
On Error GoTo 0
'Open the PDF file.
If objAcroAVDoc.Open(strFile, "") = True Then
'Set the PDDoc object.
Set objAcroPDDoc = objAcroAVDoc.GetPDDoc
'Set the JS Object - Java Script Object.
Set objJSO = objAcroPDDoc.GetJSObject
On Error GoTo 0
'Fill the form fields.
For r = 20 To 149
strField = Cells(r, 3)
strFieldVal = Cells(r, 4)
objJSO.GetField(strField).Value = CStr(strFieldVal)
If Err.Number <> 0 Then
'Close the form without saving the changes.
objAcroAVDoc.Close True
'Close the Acrobat application.
objAcroApp.Exit
'Inform the user about the error.
MsgBox "The field """ & strField & """ could not be found!", vbCritical, "Field error"
'Release the objects and exit.
Set objJSO = Nothing
Set objAcroPDDoc = Nothing
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
Exit Sub
End If
Next r
'Save the form
objAcroPDDoc.Save 1, strFile
'Close the form without saving the changes.
'objAcroAVDoc.Close True
'Close the Acrobat application.
objAcroApp.Exit
'Release the objects.
Set objJSO = Nothing
Set objAcroPDDoc = Nothing
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'Inform the user that forms were filled.
MsgBox "All forms were created successfully!", vbInformation, "Finished"
End If
MsgBox "Something bad happend :(...."
End Sub
OK... found my problem but I'm not sure how to trap the problem. I may not need to as I'm hoping I won't run into this problem. Hoping isn't the best strategy though... :)
My PDF form has fields of type numeric. All my test data in my value cells were alpha-numeric. Once I changed my quantity and cost cells to numeric values in my excel doc the form was written correctly.
Perhaps I can test for the PDF form field type. If it is numeric I'll log the field name and present a msgbox at the end of the operation that displays fields that could not be filled.
I did need to correct my objJSO line to '=strFieldVal'
I'm fairly certain you want...
strField = Cells(r, 3).Value
strFieldVal = Cells(r, 4).Value
objJSO.GetField(strField).Value = strFieldVal
...instead of the three corresponding lines you have.
Below is my final code. It includes basic error handling (more like logging). One problem I did have in this; If I was writing an alpha numeric string to the PDF field and the PDF field was numeric AND there wasn't a default value in the PDF field the PDF would throw and error that my code couldn't catch. As long as there was a default value in the PDF numeric field the error handler worked as planned. Feel free to make any comments. I'm guessing this looks like kindergarten work (maybe 1st grade??)
`Option Explicit
Sub btnToPDF_Click()
Dim objAcroApp As Object
Dim objAcroAVDoc As Object
Dim objAcroPDDoc As Object
Dim objJSO As Object
Dim fd As Office.FileDialog
Dim myWB As Workbook
Set myWB = ThisWorkbook
Dim ToPDFsh As Worksheet
Set ToPDFsh = myWB.Sheets("OSSDataDump")
Dim strFile As String
Dim strField As String
Dim strFieldVal As String 'Used to hold the field value
Dim msgFail As String
Dim colVal As Variant
Dim r As Integer 'Used to increase row number for strfield name
Dim e As Integer 'Used to track the number of errors
Dim colFail As Collection
Set colFail = New Collection
e = 0
'Disable screen flickering.
Application.ScreenUpdating = False
'Choose the Onsite Survey form you want to fill
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the On-site survey PDF."
.Filters.Clear
.Filters.Add "PDF", "*.PDF"
'If the .Show method returns False, the user clicked Cancel.
If .Show = True Then
strFile = .SelectedItems(1)
End If
End With
'Initialize Acrobat by creating the App object.
Set objAcroApp = CreateObject("AcroExch.App")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "Could not create the App object!", vbCritical, "Object error"
'Release the object and exit.
Set objAcroApp = Nothing
Exit Sub
End If
'Create the AVDoc object.
Set objAcroAVDoc = CreateObject("AcroExch.AVDoc")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "Could not create the AVDoc object!", vbCritical, "Object error"
'Release the objects and exit.
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
Exit Sub
End If
'Open the PDF file.
If objAcroAVDoc.Open(strFile, "") = True Then
'Set the PDDoc object.
Set objAcroPDDoc = objAcroAVDoc.GetPDDoc
'Set the JS Object - Java Script Object.
Set objJSO = objAcroPDDoc.GetJSObject
'Fill the form fields.
For r = 20 To 149
strField = ToPDFsh.Cells(r, 3).Value
strFieldVal = ToPDFsh.Cells(r, 4).Value
If strFieldVal = "" Then GoTo BlankVal
objJSO.GetField(strField).Value = strFieldVal
On Error GoTo ErrHandler
BlankVal:
Next r
'Save the form
objAcroPDDoc.Save 1, strFile
'Close the form without saving the changes.
'objAcroAVDoc.Close True
'Close the Acrobat application.
objAcroApp.Exit
'Release the objects.
Set objJSO = Nothing
Set objAcroPDDoc = Nothing
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'Inform the user that forms were filled.
If e <> 0 Then
For Each colVal In colFail
msgFail = msgFail & colVal & vbNewLine
Next colVal
MsgBox "Not all fields were filled" & vbNewLine & "The follwoing fields failed:" & vbNewLine & msgFail, vbExclamation, "Finished"
Exit Sub
End If
MsgBox "On site survey was filled successfully!", vbInformation, "Finished"
End If
Exit Sub
ErrHandler:
e = e + 1
If e > 7 Then
MsgBox "Something Bad happend... :(" & vbNewLine & "Form not filled", vbCritical, "Failed"
GoTo ErrHandlerExit
End If
colFail.Add strField
Resume Next
Exit Sub
ErrHandlerExit:
'Close the form without saving the changes.
objAcroAVDoc.Close True
'Close the Acrobat application.
objAcroApp.Exit
'Release the objects and exit.
Set objJSO = Nothing
Set objAcroPDDoc = Nothing
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
'Enable the screen.
Application.ScreenUpdating = True
Exit Sub
End Sub`

Tracking Chnages in Enterprise Architect

I encounter a real difficulty in tracking changes and updates in the company models.
I research the tool abilities a lot, but still didn't find the golden way that match my requirements of:
Provide indication where was a change
What was the change
Keep the original model state, aside to the up-to-date state
EA offers the following ways:
Baselines
Version Control
Clone
Change Elements
None of them provides indication on what exactly was the change and where.
What is the easiest way to manage the changes effectively?
You forgot the last resort: audit. Turn on auditing and you can get a lot more information. Of course this also has its drawbacks
it uses a lot of space
there are still changes that are not tracked in the detail you might need it.
Turn it on at Project/Auditing. More information here.
Additionally you could think of writing triggers, but I would not recommend that since it makes your repository almost unmaintainable.
Auditing is of course also no silver bullet. Tracking changes is tedious. And personally I would not spend too much effort in this "accusation mode". Better spend your energy in driving the model towards the company goals. Nobody needs yesterday's model.
I wrote some scripts to handle change management in EA.
The idea is that the user links the changed items to a change request element that represents a workitem, project, change request, bug,...
Each link contains the date, user and a comment for the change to that item.
The scripts are part of the open source EA VBScript library:
The main script is the following
'[path=\Projects\Project A\A Scripts]
'[group=Atrias Scripts]
!INC Local Scripts.EAConstants-VBScript
!INC Atrias Scripts.Util
' Script Name: LinkToCRMain
' Author: Geert Bellekens
' Purpose: Link Elemnents to a change
' Date: 2015-10-30
'
'
function linkItemToCR(selectedItem, selectedItems)
dim groupProcessing
groupProcessing = false
'if the collection is given then we initialize the first item.
if selectedItem is nothing then
if not selectedItems is nothing then
if selectedItems.Count > 0 then
set selectedItem = selectedItems(0)
if selectedItems.Count > 1 then
groupProcessing = true
end if
end if
end if
end if
if selectedItem is nothing then
set selectedItem = Repository.GetContextObject()
end if
'get the select context item type
dim selectedItemType
selectedItemType = selectedItem.ObjectType
select case selectedItemType
case otElement, otPackage, otAttribute, otMethod, otConnector :
'if the selectedItem is a package then we use the Element part of the package
if selectedItemType = otPackage then
set selectedItem = selectedItem.Element
end if
'get the logged in user
Dim userLogin
userLogin = getUserLogin
dim lastCR as EA.Element
set lastCR = nothing
dim CRtoUse as EA.Element
set CRtoUse = nothing
set lastCR = getLastUsedCR(userLogin)
'get most recent used CR by this user
if not selectedItem is nothing then
dim lastComments
lastComments = vbNullString
'if there is a last CR then we ask the user if we need to use that one
if not lastCR is nothing then
dim response
if groupProcessing then
response = Msgbox("Link all " & selectedItems.Count & " elements to change: """ & lastCR.Name & """?", vbYesNoCancel+vbQuestion, "Link to CR")
elseif not isCRLinked(selectedItem,lastCR) then
response = Msgbox("Link element """ & selectedItem.Name & """ to change: """ & lastCR.Name & """?", vbYesNoCancel+vbQuestion, "Link to CR")
end if
'check the response
select case response
case vbYes
set CRToUse = lastCR
case vbCancel
'user cancelled, stop altogether
Exit function
end select
end if
'If there was no last CR, or the user didn't want to link that one we let the user choose one
if CRToUse is nothing then
dim CR_id
CR_ID = Repository.InvokeConstructPicker("IncludedTypes=Change")
if CR_ID > 0 then
set CRToUse = Repository.GetElementByID(CR_ID)
end if
else
'user selected same change as last time. So he might want to reuse his comments as well
lastComments = getLastUsedComment(userLogin)
end if
'if the CRtoUse is now selected then we link it to the selected element
if not CRToUse is nothing then
dim linkCounter
linkCounter = 0
'first check if this CR is not already linked
if isCRLinked(selectedItem,CRToUse) and not groupProcessing then
MsgBox "The CR was already linked to this item", vbOKOnly + vbExclamation ,"Already Linked"
else
'get the comments to use
dim comments
comments = InputBox("Please enter comments for this change", "Change Comments",lastComments)
if len(comments) > 2 then
if groupProcessing then
for each selectedItem in selectedItems
'check the object type
selectedItemType = selectedItem.ObjectType
select case selectedItemType
case otElement, otPackage, otAttribute, otMethod, otConnector :
if not isCRLinked(selectedItem,CRToUse) then
linkToCR selectedItem, selectedItemType, CRToUse, userLogin, comments
linkCounter = linkCounter + 1
end if
end select
next
if linkCounter > 0 then
MsgBox "Successfully linked " & selectedItems.Count & " elements to change """ & CRToUse.Name& """" , vbOKOnly + vbInformation ,"Elements linked"
else
MsgBox "No links created to change " & CRToUse.Name & "." & vbNewLine & "They are probably already linked" , vbOKOnly + vbExclamation ,"Already Linked"
end if
else
linkToCR selectedItem, selectedItemType, CRToUse, userLogin, comments
end if
else
MsgBox "The CR has not been linked because no comment was provided", vbOKOnly + vbExclamation ,"No CR link"
end if
end if
end if
end if
case else
MsgBox "Cannot link this type of element to a CR" & vbNewline & "Supported element types are: Element, Package, Attribute, Operation and Relation"
end select
end function
function isCRLinked(item, CR)
dim taggedValue as EA.TaggedValue
isCRLinked = false
for each taggedValue in item.TaggedValues
if taggedValue.Value = CR.ElementGUID then
isCRLinked = true
exit for
end if
next
end function
function linkToCR(selectedItem, selectedItemType, CRToUse, userLogin, comments)
Session.Output "CRToUse: " & CRToUse.Name & " userLogin: " & userLogin & " comments: " & comments
dim crTag
set crTag = nothing
set crTag = selectedItem.TaggedValues.AddNew("CR","")
if not crTag is nothing then
crTag.Value = CRToUse.ElementGUID
crTag.Notes = "user=" & userLogin & ";" & _
"date=" & Year(Date) & "-" & Right("0" & Month(Date),2) & "-" & Right("0" & Day(Date),2) & ";" & _
"comments=" & comments
crTag.Update
end if
end function
function getLastUsedCR(userLogin)
dim wildcard
dim sqlDateString
if Repository.RepositoryType = "JET" then
wildcard = "*"
sqlDateString = " mid(tv.Notes, instr(tv.[Notes],'date=') + len('date='),10) "
Else
wildcard = "%"
sqlDateString = " substring(tv.Notes, charindex('date=',tv.[Notes]) + len('date='),10) "
end if
dim sqlGetString
sqlGetString = "select top 1 o.Object_id " & _
" from (t_objectproperties tv " & _
" inner join t_object o on o.ea_guid = tv.VALUE) " & _
" where tv.[Notes] like 'user=" & userLogin & ";" & wildcard & "' " & _
" order by " & sqlDateString & " desc, tv.PropertyID desc "
dim CRs
dim CR as EA.Element
set CR = nothing
'get the last CR
set CRs = getElementsFromQuery(sqlGetString)
if CRs.Count > 0 then
set CR = CRs(0)
end if
set getLastUsedCR = CR
end function
function getLastUsedComment(userLogin)
dim wildcard
dim sqlDateString
dim sqlCommentsString
if Repository.RepositoryType = "JET" then
wildcard = "*"
sqlDateString = " mid(tv.Notes, instr(tv.[Notes],'date=') + len('date='),10) "
sqlCommentsString = " mid(tv.Notes, instr(tv.[Notes],'comments=') + len('comments=')) "
Else
wildcard = "%"
sqlDateString = " substring(tv.Notes, charindex('date=',tv.[Notes]) + len('date='),10) "
sqlCommentsString = " substring(tv.Notes, charindex('comments=',tv.[Notes]) + len('comments='), datalength(tv.Notes)) "
end if
dim sqlGetString
sqlGetString = "select top 1 " & sqlCommentsString & " as comments " & _
" from (t_objectproperties tv " & _
" inner join t_object o on o.ea_guid = tv.VALUE) " & _
" where tv.[Notes] like 'user=" & userLogin & ";" & wildcard & "' " & _
" order by " & sqlDateString & " desc, tv.PropertyID desc "
dim queryResult
queryResult = Repository.SQLQuery(sqlGetString)
Session.Output queryResult
dim results
results = convertQueryResultToArray(queryResult)
if Ubound(results) > 0 then
getLastUsedComment = results(0,0)
else
getLastUsedComment = vbNullString
end if
end function

Microsoft Access - Loop through all forms and controls on each form

Okay so when I press a specific button I want to loop through all forms, then find every control in each form with the tag 'TESTING'. If the tag = 'TESTING' then I want to change the caption of the object to 'abc123'.
The only objects with the tag 'TESTING' will be labels, so they will have the caption property.
So far I have this as the function:
Public Function changelabel()
On Error Resume Next
Dim obj As AccessObject, dbs As Object
Dim ctrl as Control
Set dbs = Application.CurrentProject
For Each obj In dbs.AllForms
DoCmd.OpenForm obj.Name, acDesign
For Each ctrl In Me.Controls
If ctrl.Tag = "TESTING" Then
ctrl.Caption = "abc123"
End If
Next ctrl
Next obj
End Function
Then this as the button code:
Public Sub TestButton_Click()
Call changelabel
End Sub
So it executes the first for loop and opens all the forms in design view correctly. The problem lies with the second for loop. None of the label captions that have the tag property as 'TESTING' are changed to 'abc123'.
So what do I need to change to get the second for loop to work?
Public Sub GetForms()
Dim oForm As Form
Dim nItem As Long
Dim bIsLoaded As Boolean
For nItem = 0 To CurrentProject.AllForms.Count - 1
bIsLoaded = CurrentProject.AllForms(nItem).IsLoaded
If Not bIsLoaded Then
On Error Resume Next
DoCmd.OpenForm CurrentProject.AllForms(nItem).NAME, acDesign
End If
Set oForm = Forms(CurrentProject.AllForms(nItem).NAME)
GetControls oForm
If Not bIsLoaded Then
On Error Resume Next
DoCmd.Close acForm, oForm.NAME
End If
Next
End Sub
Sub GetControls(ByVal oForm As Form)
Dim oCtrl As Control
Dim cCtrlType, cCtrlCaption As String
For Each oCtrl In oForm.Controls
If oCtrl.ControlType = acSubform Then Call GetControls(oCtrl.Form)
Select Case oCtrl.ControlType
Case acLabel: cCtrlType = "label": cCtrlCaption = oCtrl.Caption
Case acCommandButton: cCtrlType = "button": cCtrlCaption = oCtrl.Caption
Case acTextBox: cCtrlType = "textbox": cCtrlCaption = oCtrl.Properties("DataSheetCaption")
Case Else: cCtrlType = ""
End Select
If cCtrlType <> "" Then
Debug.Print oForm.NAME
Debug.Print oCtrl.NAME
Debug.Print cCtrlType
Debug.Print cCtrlCaption
End If
Next
End Sub
Something like this
Public Function changelabel()
Dim f As Form
Dim i As Integer
Dim c As Control
For i = 0 To CurrentProject.AllForms.Count - 1
If Not CurrentProject.AllForms(i).IsLoaded Then
DoCmd.OpenForm CurrentProject.AllForms(i).Name, acDesign
End If
Set f = Forms(i)
For Each c In f.Controls
If c.Tag = "TESTING" Then
c.Caption = "TESTING"
End If
Next c
Next i
End Function
You'll need to add a bit of house-keeping to set the objects used to nothing etc..

Excel - Populate Columns with dates based on User Input

I'm reasonably proficient with Excel VBA (with lots of online help!!) ... but I've stumbled into a problem that has me completely stumped.
I'm creating a Gantt Chart for project planning. My problem is that I wish to have the user specify a project start date and a project end date then have the spreadsheet populate columns from the start date to the end date.
See basic layout:
I have already bottomed out the User Input with InputBoxes
Sub Set_Project_Start_Date()
' Written 2nd August 13
' P.J. Callaghan
'
ActiveSheet.Select
Dim projStartDate
showInputBox_Start:
projStartDate = Application.InputBox("Please enter Project Start Date" & Chr(10) & "Must be a Monday" & Chr(10) & "Format is: dd/mm/yyyy")
' Set Message Box such that clicking cancel ends the sub-routine for projStartdate variable
If projStartDate = False Then
MsgBox "You clicked the Cancel button, Input Box will close.", 64, "Cancel was clicked."
Exit Sub
ElseIf projStartDate = "" Then
MsgBox "You must click Cancel to exit.", 48, "You clicked Ok but entered nothing."
GoTo showInputBox_Start
Else
MsgBox "You entered " & projStartDate & ".", 64, "Please click OK to resume."
Range("c6").Select
With Selection
.Value = projStartDate
.NumberFormat = "dd-mmm-yy"
End With
Range("e10").Select
With Selection
.Value = projStartDate
.NumberFormat = "dd-mmm-yy"
.Orientation = 90
End With
End If
End Sub
Sub Set_Project_End_Date()
' Written 2nd August 13
' P.J. Callaghan
'
ActiveSheet.Select
Dim projEndDate
showInputBox_End:
projEndDate = Application.InputBox("Please enter Project End Date" & Chr(10) & "Must be a Monday" & Chr(10) & "Format is: dd/mm/yyyy")
' Set Message Box such that clicking cancel ends the sub-routine for projStartdate variable
If projEndDate = False Then
MsgBox "You clicked the Cancel button, Input Box will close.", 64, "Cancel was clicked."
Exit Sub
ElseIf projEndDate = "" Then
MsgBox "You must click Cancel to exit.", 48, "You clicked Ok but entered nothing."
GoTo showInputBox_End
Else
MsgBox "You entered " & projEndDate & ".", 64, "Please click OK to resume."
Range("c7").Select
With Selection
.Value = projEndDate
.NumberFormat = "dd-mmm-yy"
End With
End If
End Sub
The bit I'm stuck with is writing code to populate from the start date to the end date only. I'm sure this must be some sort of loop arrangement ... as yet I haven't figured it out.
I wondered if any of you guys could suggest a solution?
Thanks in advance,
Paul
If your goal is to populate the row that starts with cell E10 with daily dates from the start date to the end date of the project, then you can use AutoFill:
With Worksheets("Gantt")
Set sourceRange = .Range("E10")
sourceRange.Value = projStartDate
Set fillRange = .Range(sourceRange, Cells(sourceRange.Row, _
sourceRange.Column + projEndDate - projStartDate + 1))
sourceRange.AutoFill Destination:=fillRange, Type:=xlFillDays
End With
Chuff, that's right on the money.
I've taken your code and modified it slightly ... for some reason it didn't execute as a copy and paste
Sub Date_Fill()
' http://stackoverflow.com/questions/18043084/excel-populate-columns-with-dates-based-on-user-input
Dim projEndDate As Date
Dim projStartDate As Date
Dim projDuration As Integer
projStartDate = Range("c6").Value
projEndDate = Range("c7").Value
With Worksheets("Gantt")
Set SourceRange = .Range("E10")
SourceRange.Value = projStartDate
Set fillRange = .Range(SourceRange, Cells(SourceRange.Row, _
SourceRange.Column + projEndDate - projStartDate + 1))
SourceRange.AutoFill Destination:=fillRange, Type:=xlFillDays
End With
End Sub
Thank you ever so much for your assistance ... this one has been bugging me for a few weeks now. I was looking into loops today as I thought the answer may lie there.
Once again ... many thanks.