Interactive Quiz using ppt - vba

I posted a rubbish question about this before and have gone away and done some work on it to re-ask. Basically I've made a ppt quiz that counts how many correct and incorrect answers a person has given. It then feeds this information back to the user at the end. However what I want to happen now is I want the results to be stored so that I can go back in and see how each user has performed in the quiz. Ideally I would like it to work over 6 networked computers storing all the quiz results in one place. But if need be I can just take a file from each of the 6 computers.
My code so far looks like this:
Dim username As String
Dim numberCorrect As Integer
Dim numberWrong As Integer
Sub YourName()
username = InputBox(prompt:="Type your Name")
MsgBox " Get Ready to begin " + username, vbApplicationModal, " Orange 1C Book 7"
End Sub
Sub correct()
numberCorrect = numberCorrect + 1
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub incorrect()
numberWrong = numberWrong + 1
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub Start()
numberCorrect = 0
numberWrong = 0
YourName
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub Results()
MsgBox "Well done " & username & " You got " & numberCorrect & " out of " & numberCorrect + numberWrong, vbApplicationModal, "Orange 1C Book 7"
End Sub'
Any help would be greatly appreciated. Not sure where to begin with the next step.

Here goes one option for you... But some explanation first. This code will create TXT file. Each time someone will reach Results macro it will add results to the file. So, one file will keep all the results until you don't delete them (or the file). Therefore I've added separation line and date/time information for you to easily find appropriate results.
Sub Save_Results_To_Txt()
'set file results location to activepresentation path
'or could be changed to any path string
Dim strWhere As String
strWhere = ActivePresentation.Path
'let's set name of the file separately
Dim strName As String
strName = "\results.txt"
Dim ff As Long
ff = FreeFile
Open strWhere & strName For Append As #ff
Write #ff, Now & vbTab & username
Write #ff, numberCorrect & vbTab & vbTab & numberWrong
Write #ff, String(30, "-")
Close #ff
End Sub
You need to add Save_Results_To_Txt to your Results sub, possibly before MsgBox line.
Your results.txt file will look like:
"2013-04-25 16:11:05 Tom"
"10 11"
"------------------------------"
"2013-04-25 16:11:23 Mark"
"11 10"
"------------------------------"

Related

Display Excel account username in a cell on open

Working with Office 2013, I am trying to insert VBA code to automatically enter the employee name as it is displayed in the top right hand corner of any Office product into cell B2 upon them opening up the excel spreadsheet. The current code I am using is
Sub Auto_Open()
Range("B2").Value = " " & Application.UserName
End Sub
However, this just makes it display "Authorized User".
What am I doing wrong?
I poked around at this morning. I figured this information must be stored somewhere in the registry if it isn't accessible as part of the Excel object model. This makes sense, especially if this username is part of a corporate subscription.
The Registry Key
I did a search in the registry for how my username showed up in Excel, and this popped up.
The FriendlyName is exactly how my username shows up in Excel. So all we need now is a method to read this registry key's FriendlyName, and that should do it :)
Code
Here is some code that works for me based on the location of this key. It may be slightly different on your computer, so you may need to tweak this to find the FriendlyName
Private Function GetFriendlyName() As String
On Error GoTo ErrorHandler:
Const HKEY_CURRENT_USER = &H80000001
Const ComputerName As String = "."
Dim CPU As Object
Dim RegistryKeyPath As String
Dim RegistrySubKeys() As Variant
Dim RegistryValues() As Variant
Dim SubKeyName As Variant
Dim SubKeyValue As Variant
Dim KeyPath As String
GetFriendlyName = vbNullString
Set CPU = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ComputerName & "\root\default:StdRegProv")
'Specify where to look
RegistryKeyPath = "Software\Microsoft\Office\" & Application.Version & "\Common\Identity\Identities"
'Enumerate the registry keys
CPU.EnumKey HKEY_CURRENT_USER, RegistryKeyPath, RegistrySubKeys
'Iterate each key in the identities folder
For Each SubKeyName In RegistrySubKeys
'Get each value in that folder
CPU.EnumValues HKEY_CURRENT_USER, RegistryKeyPath & "\" & SubKeyName, RegistryValues
'Go through each value, and find the Friendly Name
For Each SubKeyValue In RegistryValues
If SubKeyValue = "FriendlyName" Then
KeyPath = "HKEY_CURRENT_USER\" & RegistryKeyPath & "\" & SubKeyName & "\" & SubKeyValue
'Read the key
With CreateObject("Wscript.Shell")
GetFriendlyName = .RegRead(KeyPath)
End With
Exit Function
End If
Next
Next
CleanExit:
Exit Function
ErrorHandler:
'Handle errors here
Resume CleanExit
End Function
'Run this to see the output in the immediate window
Private Sub ExampleUsage()
Debug.Print "The friendly name is: " & GetFriendlyName
End Sub
Results
The friendly name is: Ryan A. Wildry
Try this:
Sub Auto_Open()
Dim Username As String
Dim path As String
Dim sourcefile As String
Dim objFso As FileSystemObject
Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(path & " ~$" & sourcefile) Then
Username = Split(GetFileOwner(path, " ~$" & sourcefile), "\")(1)
Range("B2").Value = " " & Username
Else
MsgBox ("File not Found!")
End If
End Sub

Cannot display number values

I just joined and hope to learn all I can here and contribute where I can.
I am having major issues with the last three sections of my VBA script.
The correct, incorrect, and percentage score values are not being displayed on slides 40 & 41.
On slide 42 I cannot get the textbox or the label to display the username, date and their overall percentage score.
Any help on slide 40 would be great and I can workout the rest.
**Sub shapeTextHappySmile()**strong text**
Sub ShapeTextSadSmile()
Sub CertificateBuld()**
Option Explicit
Dim UserName As String
Dim numberCorrect As Integer
Dim numberIncorrect As Integer
Dim numberPercentage As Integer
Dim numberTotal As Integer
Private Sub CertDate()
Dim Rdate As Variant
Rdate = Date
Rdate = Format((Date), "mmmm dd, yyyy")
End Sub
Sub Initialise()
numberCorrect = 12
numberIncorrect = 8
numberPercentage = 58
numberTotal = 20
numberTotal = (numberCorrect + numberIncorrect)
numberCorrect = (numberTotal - numberIncorrect)
numberIncorrect = (numberTotal - numberCorrect)
numberPercentage = Round(numberCorrect / numberTotal) * 100
End Sub
Sub TakeQuiz()
UserName = InputBox(Prompt:="Type Your Name! ")
MsgBox "Welcome To The Academic Online Tutorial Quiz " + UserName, vbApplicationModal, " Academic Online Tutorial Quiz"
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub Correct()
numberCorrect = numberCorrect + 1
MsgBox ("Great well Done! That's the correct answer")
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub Incorrect()
numberIncorrect = numberIncorrect + 1
MsgBox ("Sorry! That was the incorrect answer")
ActivePresentation.SlideShowWindow.View.Next
End Sub
Sub shapeTextHappySmile()
ActivePresentation.Slides(40).Shapes(Label1).TextFrame.TextRange.Text = 12
'numberCorrect
ActivePresentation.Slides(40).Shapes(Label2).TextFrame.TextRange.Text = numberPercentage & "%"
MsgBox "Great Job, Well done " + "," & "Please print a copy of your completion certificate"
MsgBox "After printing or saving a copy of your certificate, you can exit the presentation"
With SlideShowWindows(1).View
.GotoSlide 42
End With
End Sub
Sub ShapeTextSadSmile()
ActivePresentation.Slides(41).Shapes("AnsweredIncorrectly").TextFrame.TextRange.Text = numberIncorrect
ActivePresentation.Slides(41).Shapes("InCorrectPercentage").TextFrame.TextRange.Text = numberPercentage & " %"
MsgBox "Your score was below 70%, in order to pass the quiz and receive a certificate of completion you need to score 70% or more."
MsgBox "Please retake the quiz, and good luck"
With SlideShowWindows(1).View
.GotoSlide 1
End With
' I will add the option of redoing the entire presentation or just the quiz.
'see slide 19 action buttons
End Sub
Sub CertificateBuld()
MsgBox "Great Job, Well done " + "," & "Plese print a copy of your completion certificate"
MsgBox "After printing or saving a copy of your certificate, please exit the presentation"
If numberCorrect >= "14" Then
ActivePresentation.Slides(42).Shapes(" ABCDEFGHIJKLMN ").TextFrame.TextRange.Text = " ABCDEFGHIJKLMN "
ActivePresentation.Slides(42).Shapes("Rdate & Percentage").TextFrame.TextRange.Text = " ON " & Rdate & " WITH A SCORE OF " & numberPercentage & " %"
ActivePresentation.Slides(42).Shapes(UserName).TextFrame.TextRange.Text = UserName
'OR
If numberCorrect <= "14" Then
ActivePresentation.Slides(42).Shapes(8).TextFrame.TextRange.Text = ABCDEFGHIJKLMN "
ActivePresentation.Slides(42).Shapes(9).TextFrame.TextRange.Text = Rdate & " ON " & Rdate & " WITH A SCORE OF " & numberPercentage & " %"
ActivePresentation.Slides(42).Shapes(10).TextFrame.TextRange.Text = UserName
Else
ActivePresentation.SlideShowWindow.View.Save
ActivePresentation.SlideShowWindow.View.Exit
End If
End Sub
See comments inline:
Sub shapeTextHappySmile()
' This won't work:
'ActivePresentation.Slides(40).Shapes(Label1).TextFrame.TextRange.Text = 12
' Shapes have names that are strings, so you need to use .Shapes("Label1")
' Assuming this is an ActiveX label, you get at its properties a bit
' differently from regular PPT shapes, starting with:
' .Shapes("Label1").OLEFormat.Object
' And for a Label ActiveX control, the property you want is .Caption
' And finally, Text/Caption properties take a String value so you want to
' put the 12 in quotes or convert a numeric value to string using Cstr(x)
' Final version:
ActivePresentation.Slides(40).Shapes("Label1").OLEFormat.Object.Caption = "12"
'numberCorrect
' And make the same changes to this one:
ActivePresentation.Slides(40).Shapes(Label2).TextFrame.TextRange.Text = numberPercentage & "%"
' MsgBox "Great Job, Well done " + "," & "Please print a copy of your completion certificate"
' and I think you probably want to do this instead of the above:
MsgBox "Great Job, Well done" & ", " & "Please print a copy of your completion certificate"
MsgBox "After printing or saving a copy of your certificate, you can exit the presentation"
With SlideShowWindows(1).View
.GotoSlide 42
End With
End Sub

Message Box referring to cell contents

I cant get the syntax right for a msgbox. I want the box to say:
You have indicated that"
"employee name" (a range reference to a cell the worksheet)
has worked for "hours" (a range reference to a cell the worksheet) doing "job" (a range reference to a cell the worksheet)
Is this information correct?
This is what I have (shortened slightly):
Public confirmation_yes_no()
Dim yesornoanswertomessagebox As String
Dim questiontomessagebox As String
questiontomessagebox = "You have indicated that" & worksheets("dept 1 input").range("g12"),"worked at" & worksheets("dept 1 input").range("g16"), "for" & worksheets("dept 1 input").range("g16"), vbinformation, "Are you sure that this data is correct?"
yesornoanswertomessagebox = MsgBox(questiontomessagebox, vbYesNo, "FlightPlan for Profits PRO")
If yesornoanswertomessagebox = vbNo Then
MsgBox "Return to Data Input to correct error(s)", 0, "FlightPlan for Profits PRO"
Else
MsgBox "Great! Press Enter", 0, "FlightPlan for Profits PRO"
End If
End Sub
I am assuming, of course, that this is possible.
Couple of things with your code,
The opening line of your sub, Public confirmation_yes_no(), what is it, is it a sub, function or what, the way it's written right now it is a global variable declaration.
When combining elements into one like with your string, always use & but be sure to manually put spaces around it, otherwise it is not recognized. &var1 <> & var1
Be cautious when setting the arguments in a variable to be used later and definitely don't set them twice.
If you use a qualifier a lot, like Worksheets("dept 1 input"), consider using a With statement like below, this saves you from having to type the bit on the With statement over and over. Please note that to make use of the with statement, you write . in front of the code..Range(... points to the sheet which is set by the With statement.Range(... points to the sheet which Excel considers to be active.
When combining variables with text, take into account that the variables most likely do not have leading and trailing spaces, and that you'll have to compensate for this in the string bits.
for readability you can add an _ to your code to indicate it continues on the next line instead of having a very, very long line.
You can use a message box directly in an If statement.
Corrected code
Public Sub confirmation_yes_no()
Dim questiontomessagebox As String
With ThisWorkbook.Worksheets("dept 1 input")
questiontomessagebox = "You have indicated that " & .Range("G12") & " worked at " _
& .Range("G16") & " for " & .Range("G16") & "." _
& vbCr & vbCr _
& "Are you sure that this data is correct?"
End With
If MsgBox(questiontomessagebox, vbYesNo, "FlightPlan for Profits PRO") = vbNo Then
MsgBox "Return to Data Input to correct error(s)", 0, "FlightPlan for Profits PRO"
Else
MsgBox "Great! Press Enter", 0, "FlightPlan for Profits PRO"
End If
End Sub
Hi you missed the "&" signs. So i Correct it for you.
questiontomessagebox = ("You have indicated that " & Worksheets("dept 1 input").Range("g12") & " ,worked at " _
& Worksheets("dept 1 input").Range("g16") & " for " & Worksheets("dept 1 input").Range("g16")) & Chr(32) & _
vbInformation & vbNewLine & " Are you sure that this data is correct?"

Excel vba open all word document in a folder and print by getting number of copies from user

I am new to Macro
By googling I coded this and I have changed some part for my use.
Problem is Runtime error is coming. And I don't know how to print all word documents in folder both .doc and .docx
My Requirement
Want to print all word document in folder A (both .doc and .docx).
Print active document ( Number of copies want to be get from User ).
Close active document.
Repeat 2 and 3 for all document in folder A
My code will get page number to print from case selected by the user
case 1 will print 1st two pages one by one.
case 2 will print 3rd to reset of the pages.
case 3 will print full document.
In my office duplex is default printer setup to print. But I will be using letter head. I need this macro to solve my issue. I tried simplex macro code to print but its not working.
Sub prnt()
Dim c As Integer
Dim i As Integer
Dim strName As String
'get print type
strName = InputBox(Prompt:="Choose Your Option" & vbNewLine & "" & vbNewLine & "1. Letter Head" & vbNewLine & "2. A4 Sheet" & vbNewLine & "3. Comp Plan" & vbNewLine & "", _
Title:="ENTER YOUR PRINT TYPE", Default:="Your Choice here")
If strName = "Your Choice here" Or strName = vbNullString Then
MsgBox "Sorry...! Choose Correct option"
Exit Sub
Else
'case to choose option
Select Case strName
Case "1"
Dim file
Dim path As String
Dim ans As String
'get number of copies from user
c = InputBox("Please enter number of copies")
ans = MsgBox("Are you sure you want to print " & _
c & "?", _
vbQuestion + vbYesNo, "Print pages")
If ans = vbNo Then
Exit Sub
Else
'path to the folder
path = "E:\print\"
file = Dir(path & "*.docx")
Do While file ""
Documents.Open Filename:=path & file
For i = 1 To 2 'loop 2 pages
ActiveDocument.PrintOut , Copies:=c, Range:=wdPrintRangeOfPages, Pages:=i
Next
ActiveDocument.Close
' set file to next in Dir
file = Dir()
Loop
End If
Case "2"
Case "3"
Case Else
MsgBox "Sorry...! Choose Correct option"
End Select
End If
End Sub
There's bad programming practice to work on strings instead of numbers.
See this:
Sub Test()
Dim noofcopies As Integer
noofcopies = GetNumberOfCopies()
MsgBox noofcopies
End Sub
Function GetNumberOfCopies() As Integer
Dim iRetVal As Integer
On Error GoTo Err_GetNumberOfCopies
iRetVal = CInt(InputBox("Enter no. of copies to print" & vbCr & vbCr & _
"Enter proper integer value between 1 and 3" & vbCr & _
"0 (zero) equals to Cancel", "No. of copies", "1"))
If iRetVal > 3 Then iRetVal = 3
Exit_GetNumberOfCopies:
GetNumberOfCopies = iRetVal
Exit Function
Err_GetNumberOfCopies:
Err.Clear
Resume 0
End Function
Use the same logic to get print option ;)

adding multiple messgeboxes values to single messagebox in vba

I have this code with me where i can display the message when every outer loop ends. I want to catch all these messages in suppose array or soome list like structure and then at the end want to display each of these messages into one msgbox. Would appreciate if someone could help me.
Thanks.
For Each objNavFolder In objNavGroup.NavigationFolders
SkippedItemCounter = 0
If oItems.Count = 0 Then
MsgBox "No Appointments items in " & objNavFolder.DisplayName & "'s folder"
Else
NextRow = NextRow + 1
For Each MyItem In oItems
If MyItem = "" Then
SkippedItemCounter = SkippedItemCounter + 1
End If
'some code here
Next
Set objExpl = _colExpl.Add(objFolder, olFolderDisplayNormal)
NextRow = NextRow - 1
End If
MsgBox "No. of items= "&SkippedItemCounter&"skipped from"&objNavFolder.DisplayName&""
Next
End If
End If
End If
instead of calling msgboxes, create a String and keep adding the messages - at the end of code msgbox(yourString)
for example
decalare a string before the main sub
Dim yourFinalMessage As String ' or Dim yourFinalMessage$
instead of
MsgBox "No Appointments items in " & objNavFolder.DisplayName & "'s folder"
say
yourFinalMessage = yourFinalMessage & vbCrLf & & _
"No Appointments items in " & objNavFolder.DisplayName & "'s folder"
keep doing this until the loop ends.
at the end of loop say
msgbox YourFinalMessage
Not sure to exactly understand what you want, but you might try to add this to a module:
Option Explicit
Dim globalMsg as String
globalMsg = ""
Function customMsg(msg as String)
MsgBox msg
globalMsg = globalMsg & VbCrLf & msg
End Function
Just call customMsg("Your Message") to display a MsgBox and at the end, call MsgBox globalMsg to display all the messages as a single message (one per line). There are a lot of other ways to do this, it depends on you. Please be more explicit if you want any further help.