BritsBlitz
New Member
- Joined
- Jan 10, 2014
- Messages
- 34
- Office Version
- 365
- Platform
- Windows
HI, I'm new to VBA and wrote a very simple code to pull data from a survey and store it in a text file. The code is pasted below. I'd like to know if there is a way to simplify the code using For loops to step through the objTs.WriteLine commands and increment the number at the end of the OptionButtons instead of having 9 lines in the code.
Private Sub CommandButton1_Click()
Dim objFSO As Scripting.FileSystemObject
Dim objTS As Scripting.TextStream
' Create the text file.
Set objFSO = New Scripting.FileSystemObject
Set objTS = objFSO.OpenTextFile(CurDir & "/Survey_Results.txt", ForAppending, True)
' Write the results to the text file and then close the file.
'Question 1
objTS.WriteLine "Answer = " & Me.OptionButton1.Value
objTS.WriteLine "Answer = " & Me.OptionButton2.Value
objTS.WriteLine "Answer = " & Me.OptionButton3.Value
objTS.WriteLine "Answer = " & Me.OptionButton4.Value
objTS.WriteLine "Answer = " & Me.OptionButton5.Value
objTS.WriteLine "Answer = " & Me.OptionButton6.Value
objTS.WriteLine "Answer = " & Me.OptionButton7.Value
objTS.WriteLine "Answer = " & Me.OptionButton8.Value
objTS.WriteLine "Answer = " & Me.OptionButton9.Value
objTS.WriteBlankLines 1
objTS.Close
' Thank the user.
MsgBox "Thanks for your feedback."
' Clear the results for next time.
Me.OptionButton1.Value = False
Me.OptionButton2.Value = False
Me.OptionButton3.Value = False
Me.OptionButton4.Value = False
Me.OptionButton5.Value = False
Me.OptionButton6.Value = False
Me.OptionButton7.Value = False
Me.OptionButton8.Value = False
Me.OptionButton9.Value = False
Application.Quit
End Sub
Private Sub CommandButton1_Click()
Dim objFSO As Scripting.FileSystemObject
Dim objTS As Scripting.TextStream
' Create the text file.
Set objFSO = New Scripting.FileSystemObject
Set objTS = objFSO.OpenTextFile(CurDir & "/Survey_Results.txt", ForAppending, True)
' Write the results to the text file and then close the file.
'Question 1
objTS.WriteLine "Answer = " & Me.OptionButton1.Value
objTS.WriteLine "Answer = " & Me.OptionButton2.Value
objTS.WriteLine "Answer = " & Me.OptionButton3.Value
objTS.WriteLine "Answer = " & Me.OptionButton4.Value
objTS.WriteLine "Answer = " & Me.OptionButton5.Value
objTS.WriteLine "Answer = " & Me.OptionButton6.Value
objTS.WriteLine "Answer = " & Me.OptionButton7.Value
objTS.WriteLine "Answer = " & Me.OptionButton8.Value
objTS.WriteLine "Answer = " & Me.OptionButton9.Value
objTS.WriteBlankLines 1
objTS.Close
' Thank the user.
MsgBox "Thanks for your feedback."
' Clear the results for next time.
Me.OptionButton1.Value = False
Me.OptionButton2.Value = False
Me.OptionButton3.Value = False
Me.OptionButton4.Value = False
Me.OptionButton5.Value = False
Me.OptionButton6.Value = False
Me.OptionButton7.Value = False
Me.OptionButton8.Value = False
Me.OptionButton9.Value = False
Application.Quit
End Sub