I've created this 2 player game called Go and I've made it so that the statistics from the game is recorded in a text file. If the same 2 players play each other more than once, their game will be recorded in the same text file on the next line.
I have done all of that, but now I want the previous games to be displayed on screen so that the players can see the scores from previous matches. I don't want the final line to be displayed as that is the score from the game that has just finished. Here's my code so far:
Dim file As System.IO.StreamWriter
'Imports the data from previous forms to form 3
handikomi = Form1.handi_komi
prisonerB = Form2.prisonerB
prisonerW = Form2.prisonerW
bpass = Form2.bpass
wpass = Form2.wpass
bstones = Form2.bstones
wstones = Form2.wstones
btotalscore = prisonerB + handikomi(0, 2)
wtotalscore = prisonerW + handikomi(1, 2)
If btotalscore > wtotalscore Then
winnerlbl.Text = (handikomi(0, 0) & " IS THE WINNER!")
ElseIf wtotalscore > btotalscore Then
winnerlbl.Text = (handikomi(1, 0) & " IS THE WINNER!")
End If
file = My.Computer.FileSystem.OpenTextFileWriter("F:\My Go project flood fill2\Text files\" & handikomi(0, 0) & " VS " & handikomi(1, 0) & ".txt", True)
'Displays statistics from current match
file.WriteLine("BLACK" & "," & "WHITE" & "," & "Total Score" & "," & btotalscore & "," & wtotalscore & "," & "Prisoners" & "," & prisonerB & "," & prisonerW & "," & "Passes" & "," & bpass & "," & wpass & "," & "Stones" & "," & bstones & "," & wstones)
file.Close()
breakdwnlbl.Text = " BLACK WHITE"
breakdwnlbl.Text = (breakdwnlbl.Text & vbNewLine & "Total Score" & " " & btotalscore & " " & wtotalscore)
breakdwnlbl.Text = (breakdwnlbl.Text & vbNewLine & "Prisoners" & " " & prisonerB & " " & prisonerW)
breakdwnlbl.Text = (breakdwnlbl.Text & vbNewLine & "Passes" & " " & bpass & " " & wpass)
breakdwnlbl.Text = (breakdwnlbl.Text & vbNewLine & "Stones" & " " & bstones & " " & wstones)
Dim data As String 'to hold value of file line
Dim filename As String 'declare file
filename = "F:\My Go project flood fill2\Text files\" & handikomi(0, 0) & " VS " & handikomi(1, 0) & ".txt" 'path to file on system
FileOpen(1, filename, OpenMode.Input) 'open file for reading
'try amend
Do While Not EOF(1)
data = LineInput(1)
MsgBox(data)
Loop
I think that I shouldn't be using EOF for this case, but I don't know what else to use as I'm still a beginner. I appreciate any help!
Wouldn't it be easier to read all lines and just skip the last one:
Dim allLines() As String = File.ReadAllLines(filename)
Dim allButLast = allLines.Take(allLines.Length - 1)
The variable allButLast is an IEnumerable(Of String) containing all the lines of the file, except for the last one.
Update:
Here's an example to show each line in a MessageBox:
For Each line As String In allButLast
MessageBox.Show(line)
Next
Related
This code is designed to detect the columns of start and finish of a shape which is used and displayed onto the caption of the shape itself. The following code is the problematic code:
Sub Take_Baseline()
Dim forcast_weeksStart() As String
Dim forcast_weeksEnd() As String
Dim forcastDate As String
Dim shp As Shape
Dim split_text() As String
'cycle through all the shapes in the worsheet and enter the forcast date for all the projects into their respective boxes
For Each shp In ActiveSheet.Shapes
'initialize forcast date by parsing
forcast_weeksStart = Split(shp.TopLeftCell.Column.Text, " ")
forcast_weeksEnd = Split(shp.BottomRightCell.Column.Text, " ")
forcastDate = forcast_weeksStart(1) & "-" & forcast_weeksEnd(1)
temp = shp.OLEFormat.Object.Object.Caption
If InStr(temp, "/-/") > 0 & InStr(temp, "In Prog") Then
split_text = Split(shp.OLEFormat.Object.Caption, " ")
For i = 0 To (i = 3)
shp.TextFrame.Characters.Caption = split_text(i) & vbNewLine
Next i
ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption = ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption & vbNewLine & ActiveSheet.Cells(4, AShape.TopLeftCell.Column).Text & " - " & ActiveSheet.Cells(4, AShape.BottomRightCell.Column).Text & vbNewLine & "dates: " & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & "/" & "actualDate"
' ElseIf InStr(temp, "/-/") > 0 & InStr(temp, "In Prog") = 0 Then
'split_text = Split(shp.OLEFormat.Object.Object.Caption, " ")
' For i = 0 To (i = 2)
' shp.OLEFormat.Object.Caption = split_text(i) & vbNewLine
' Next i
'ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption = ActiveSheet.Shapes(Sheet4.Range("B1")).TextFrame.Characters.Caption & vbNewLine & "In Prog" & vbNewLine & ActiveSheet.Cells(4, AShape.TopLeftCell.Column).Text & " - " & ActiveSheet.Cells(4, AShape.BottomRightCell.Column).Text & vbNewLine & "dates: " & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & forcast_weeksStart(1) & " - " & forcast_weeksEnd(1) & "/" & "actualDate"
End If
Next shp
'For testing purposes
Sheet4.Range("A20").Value = forcast_weeksStart(1)
Sheet4.Range("A21").Value = forcast_weeksEnd(1) End Sub
The error is an
"invalid qualifier"
message which occurs on line
forcast_weeksStart = Split(shp.TopLeftCell.Column.Text, " ")
Right on the "column" word. I don't get why this is happening since the actual drop down menu has the column operation which i can select. I have tried everything from changing it to the OLEformat.Object.Caption etc etc. But nothing has worked. I am still relatively new to vba so any help will be appreciated. Thanks
I have a VBA that creates a new directory folder and creates a new text file in that directory. I am trying to run a perl script from the VBA and have created a batch file that gets called from the VBA. That bat file uses a shell file to run a script. The directory in the script is dynamic and changes each time based on user input. My question is can the .sh file be updated before it is run? I apologize for the long post, just wanted to be complete. Thank you :).
VBA
Private Sub CommandButton3_Click()
Dim MyBarCode As String ' Enter Barcode
Dim MyScan As String ' Enter ScanDate
Dim MyDirectory As String
MyBarCode = Application.InputBox("Please enter the barcode", "Bar Code", Type:=2)
If MyBarCode = "False" Then Exit Sub 'user canceled
Do
MyScan = Application.InputBox("Please enter scan date", "Scan Date", Date, Type:=2)
If MyScan = "False" Then Exit Sub 'user canceled
If IsDate(MyScan) Then Exit Do
MsgBox "Please enter a valid date format. ", vbExclamation, "Invalid Date Entry"
Loop
Range("B20").Value = MyBarCode
Range("B21").Value = CDate(MyScan)
MyDirectory = "N:\1_DATA\MicroArray\NexusData\" & MyBarCode & "_" & Format(CDate(MyScan), "m-d-yyyy") & "\"
' Create nexus directory and folder
If Dir(MyDirectory, vbDirectory) = "" Then MkDir MyDirectory
If MsgBox("The project file has been created. " & _
"Do you want to create a template for analysis now?", _
vbQuestion + vbYesNo) = vbYes Then
'Write to text file
Open MyDirectory & "sample_descriptor.txt" For Output As #1
Print #1, "Experiment Sample" & vbTab & "Control Sample" & vbTab & "Display Name" & vbTab & "Gender" & vbTab & "Control Gender" & vbTab & "SpikeIn Location"
Print #1, MyBarCode & "_532Block1.txt" & vbTab & MyBarCode & "_635Block1.txt" & vbTab & ActiveSheet.Range("B8").Value & " " & ActiveSheet.Range("B9").Value & vbTab & ActiveSheet.Range("B10").Value & vbTab & ActiveSheet.Range("B5").Value & vbTab & ActiveSheet.Range("B11").Value & vbTab & ActiveSheet.Range("B12").Value
Print #1, MyBarCode & "_532Block2.txt" & vbTab & MyBarCode & "_635Block2.txt" & vbTab & ActiveSheet.Range("C8").Value & " " & ActiveSheet.Range("C9").Value & vbTab & ActiveSheet.Range("C10").Value & vbTab & ActiveSheet.Range("C5").Value & vbTab & ActiveSheet.Range("C11").Value & vbTab & ActiveSheet.Range("C12").Value
Print #1, MyBarCode & "_532Block3.txt" & vbTab & MyBarCode & "_635Block3.txt" & vbTab & ActiveSheet.Range("D8").Value & " " & ActiveSheet.Range("D9").Value & vbTab & ActiveSheet.Range("D10").Value & vbTab & ActiveSheet.Range("D5").Value & vbTab & ActiveSheet.Range("D11").Value & vbTab & ActiveSheet.Range("D12").Value
Print #1, MyBarCode & "_532Block4.txt" & vbTab & MyBarCode & "_635Block4.txt" & vbTab & ActiveSheet.Range("E8").Value & " " & ActiveSheet.Range("E9").Value & vbTab & ActiveSheet.Range("E10").Value & vbTab & ActiveSheet.Range("E5").Value & vbTab & ActiveSheet.Range("E11").Value & vbTab & ActiveSheet.Range("E12").Value
Close #1
'Run ImaGene
If MsgBox("Please run the ImaGene analysis. " & _
"and click yes after it completes to verify the spike-ins.", _
vbQuestion + vbYesNo) = vbYes Then
**'Update folder structure and call .bat
Dim PathCrnt As String
Dim FN As Long
FN = FreeFile 'FreeFile gets an available file number'
Open "C:\cygwin\home\cmccabe\Run_probes.sh" For Output As FN
PathCrnt = ActiveWorkbook.Path
*system.diagnostics.process.Start ("C:\Users\cmccabe\Desktop\NxClinical.bat") & PathCrnt*
Close FN
End If**
End Sub
Else
MsgBox "Nothing has been done. ", vbExclamation, "Goodbye!"
End If
Application.DisplayAlerts = False
Application.Quit
End Sub
Bat with that calls perl script:
C:\cygwin\bin\bash --login -i ./Run_probes.sh
Run_probes.sh
perl "C:\cygwin\home\cmccabe\get_imagene_spikein_probe_values.pl" "N:\1_DATA\MicroArray\NexusData\*257168310045_8-18-2015*" "ImaGene EmArray- Template.txt" < test_probes8.txt > "N:\1_DATA\MicroArray\NexusData\*257168310045_8-18-2015*\output.txt"
Nice post! Very detailed. :)
Certainly the Perl file can be updated before it is run. Just write the update path into the file like you write the data into sample_descriptor.txt. eg:
Dim FN as Long
FN = FreeFile 'FreeFile gets an available file number'
Open PathToShFile For Output As FN
Print FN, "perl " & chr(34) & PathCrnt & _
& chr(34) & "\get_imagene_spikein_probe_values.pl" & chr(34) & _
& chr(34) & "N:\1_DATA\MicroArray\NexusData\*257168310045_8-18-2015*" & _
chr(34) & " " & chr(34) & _
" ImaGene EmArray- Template.txt" & chr(34) & _
" < test_probes8.txt > " & chr(34) & _
"N:\1_DATA\MicroArray\NexusData\*257168310045_8-18-2015*\output.txt" & chr(34)
Close FN
I'm not sure I got all the " marks replaced with chr(34) correctly so make sure to echo out that string before trying to execute any code. You might also make it more readable (and configurable) by using variables to store paths. eg:
strNPath = "N:\1_DATA\MicroArray\NexusData\*257168310045_8-18-2015*\"
here is my code to submit data to my csv file. How do I check to see if the data already exists before saving it.
Dim csvFile As String = My.Application.Info.DirectoryPath & "\HoseData.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
'If My.Computer.FileSystem.FileExists(csvFile) Then
'outFile.WriteLine("job number, sales order number, date, requested by, serial number, hose type, hose size, fitting 1, fitting 2, qty, oal, cut off, offset, crimp 1, crimp 2, cleaned, pigged", False)
'End If
outFile.WriteLine(TextBox1.Text & "," & TextBox2.Text & "," & """" & DateTimePicker1.Text & """" & "," & ComboBox1.Text & "," & TextBox3.Text & "," & ListBox2.Text & "," & ListBox3.Text & "," & TextBox11.Text & "," & TextBox12.Text & "," & NumericUpDown1.TextAlign & "," & TextBox4.Text & "," & TextBox5.Text & "," & TextBox6.Text & "," & TextBox9.Text & "," & TextBox10.Text & "," & ListBox4.Text & "," & ListBox5.Text)
MessageBox.Show("INPUT WAS SAVED")
Dim butt As System.Windows.Forms.Button = DirectCast(sender, System.Windows.Forms.Button)
butt.Enabled = False
'butt.Visible = False
outFile.Close()
Console.WriteLine(My.Computer.FileSystem.ReadAllText(csvFile))
Is this what you're looking for?
Dim fn As String = My.Application.Info.DirectoryPath & "\HoseData.csv"
Dim fileText As String
Dim outString As String = TextBox1.Text & "," & TextBox2.Text & "," & """" & DateTimePicker1.Text & """" & "," & ComboBox1.Text & "," & TextBox3.Text & "," & ListBox2.Text & "," & ListBox3.Text & "," & TextBox11.Text & "," & TextBox12.Text & "," & NumericUpDown1.TextAlign & "," & TextBox4.Text & "," & TextBox5.Text & "," & TextBox6.Text & "," & TextBox9.Text & "," & TextBox10.Text & "," & ListBox4.Text & "," & ListBox5.Text
Using reader As StreamReader = File.OpenText(fn)
fileText = reader.ReadToEnd
End Using
Using outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(fn, True)
If fileText.Contains(outString) Then
'do stuff when the string is already present, e.g.:
MessageBox.Show("You've already entered that one.")
Else
'do stuff when it isn't, e.g.:
outFile.WriteLine(outString)
End If
End Using
the below code is run from a double click event on a listbox that copies the selected file to the selected node directory on a treeview then adds the selected text as a child node.
It appears to work fine however when the program is closed and then re-opened its not showing the child node.
Any pointers........
Dim Copy2 = aMailbox & tvProgress.SelectedNode.Text & "\" & lstRequired.Text
Dim Copy1 = rPath & "\" & lstRequired.Text
If File.Exists(Copy2) Then
MsgBox("File already added. Please edit from the view above", MsgBoxStyle.OkOnly, "Lynx Control Panel")
Exit Sub
End If
If File.Exists(Copy1) Then
File.Copy(Copy1, Copy2)
tvProgress.SelectedNode.Nodes.Add(lstRequired.Text)
tvProgress.ExpandAll()
Else
MsgBox("This file no longer exists in your Lynx Repository. Please select another", MsgBoxStyle.OkOnly, "Lynx Control Panel")
Exit Sub
End If
The below code is taken entirely from a doubleclick event of the 1st listbox
Dim n As Integer
Dim i As Integer = lstPlanned.SelectedIndex
If lstPlanned.SelectedItems.Count = 0 Then Exit Sub
For n = 0 To UBound(AllDetails)
If AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps = lstPlanned.SelectedItem Then
If Not My.Computer.FileSystem.DirectoryExists(zMailbox & AllDetails(n).uFile) Then
MsgBox("No files located for " & vbNewLine & (AllDetails(n).uName & " (" & AllDetails(n).uCode) & ")" & vbNewLine & " " & vbNewLine & "Please try another...", MsgBoxStyle.OkOnly, "Lynx Control Panel")
Exit Sub
End If
System.IO.Directory.CreateDirectory(aMailbox & "\" & AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps)
For Each f In Directory.GetFiles(zMailbox & AllDetails(n).uFile, "*.dbf")
If File.Exists(f) Then
File.Copy(f, Path.Combine(aMailbox & "\" & AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps, Path.GetFileName(f)), True)
End If
Next
For Each f In Directory.GetFiles(zMailbox & AllDetails(n).uFile, "*.ini", SearchOption.AllDirectories)
If File.Exists(f) Then
File.Copy(f, Path.Combine(aMailbox & "\" & AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps, Path.GetFileName(f)), True)
End If
Next
For Each f In Directory.GetFiles(zMailbox & AllDetails(n).uFile, "*.txt", SearchOption.AllDirectories)
If File.Exists(f) Then
File.Copy(f, Path.Combine(aMailbox & "\" & AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps, Path.GetFileName(f)), True)
End If
Next
tvProgress.Nodes.Remove(rN)
tvProgress.Nodes.Insert(0, rN)
tvProgress.Nodes.Add(New TreeNode(AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps))
If i >= 0 And i < lstPlanned.Items.Count Then
lstPlanned.Items.RemoveAt(i)
End If
Exit Sub
End If
Next
Think that's want you want..maybe ;)
...
System.IO.Directory.CreateDirectory(aMailbox & "\" & AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps)
' After the Dir is created Node is added to the TreeView
tvProgress.Nodes.Remove(rN)
tvProgress.Nodes.Insert(0, rN)
tvProgress.Nodes.Add(New TreeNode(AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps))
For Each f In Directory.GetFiles(zMailbox & AllDetails(n).uFile, "*.dbf")
If File.Exists(f) Then
File.Copy(f, Path.Combine(aMailbox & "\" & AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps, Path.GetFileName(f)), True)
'As ParentNode already exists as Pos 0 you can add child nodes to it
tvProgress.Nodes(0).Nodes.Add(Path.GetFileName(f))
End If
Next
...
below is my code, which isn't perfect but working, it take more than 30min to loop through a text file. how to improve the speed of looping through file by using other code or method. please help.
Open "C:\Users\steven.EOPESTATE\Desktop\Sharp Sales\TRMSAVE01.txt" For Input As #1
Do Until EOF(1)
Dim ITEMSQL As String
Line Input #1, varLine
testvarline = Split(varLine, ",")
If testvarline(0) = "$ITEM" Then
'Debug.Print testvarline(0), testvarline(1), testvarline(2), testvarline(3), testvarline(4), testvarline(5), testvarline(6), testvarline(7), testvarline(8), testvarline(9)
testvarline(0) = Replace(testvarline(0), "$", " ")
testvarline(7) = Replace(testvarline(7), ",,", " ")
ITEMSQL = "Insert into SalesItem([ITEMID], [2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]) Values (" & Chr(34) & "" & (testvarline(0)) & "" & Chr(34) & "," & (testvarline(1)) & "," & (testvarline(2)) & "," & (testvarline(3)) & "," & (testvarline(4)) & "," & (testvarline(5)) & "," & Chr(34) & "" & (testvarline(6)) & "" & Chr(34) & "," & (testvarline(9)) & "," & (testvarline(10)) & "," & (testvarline(11)) & "," & (testvarline(12)) & "," & (testvarline(14)) & ")"
Debug.Print ITEMSQL
DoCmd.RunSQL ITEMSQL
DoCmd.SetWarnings False
DoCmd.Echo False
End If
Loop
Close #1
One of the slowest things you can do on a pc is load from the hard drive. The CPU and RAM are incredibly much faster than the hard drive (see this SO question), so they end up waiting for a hard disk read to complete. Because of this, reading the entire file into memory at once will speed up your program significantly.
Rather than use the Split function again to split up the lines for processing, I recommend parsing them yourself by using the Mid function, which actually avoids a lot of the overhead of normal string processing because it doesn't create a temporary copy of the substring in memory. Here is UNTESTED example code:
Dim strFileText As String
Dim lngCurrIndex As Long
Dim lngEndOfLine As Long
Open "C:\Users\steven.EOPESTATE\Desktop\Sharp Sales\TRMSAVE01.txt" For Binary As #1
strFileText = Space(LOF(1)) 'create space for the whole file'
Get 1, , strFileText 'read in the whole file at once'
lngCurrIndex = 1
Do While lngCurrIndex < Len(strFileText)
Dim ITEMSQL As String
lngEndOfLine = InStr(lngCurrIndex, strFileText, vbCrLf, vbBinaryCompare) 'find the end of this line. NOTE: This assumes that this text files uses the MS convention of CrLf line endings'
varLine = Mid(strFileText, lngCurrIndex, lngEndOfLine - lngCurrIndex) 'get the line'
lngCurrIndex = lngEndOfLine + 2 'set lngCurrIndex to the start of the next line'
testvarline = Split(varLine, ",")
If testvarline(0) = "$ITEM" Then
'Debug.Print testvarline(0), testvarline(1), testvarline(2), testvarline(3), testvarline(4), testvarline(5), testvarline(6), testvarline(7), testvarline(8), testvarline(9)'
testvarline(0) = Replace(testvarline(0), "$", " ")
testvarline(7) = Replace(testvarline(7), ",,", " ")
ITEMSQL = "Insert into SalesItem([ITEMID], [2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]) Values (" & Chr(34) & "" & (testvarline(0)) & "" & Chr(34) & "," & (testvarline(1)) & "," & (testvarline(2)) & "," & (testvarline(3)) & "," & (testvarline(4)) & "," & (testvarline(5)) & "," & Chr(34) & "" & (testvarline(6)) & "" & Chr(34) & "," & (testvarline(9)) & "," & (testvarline(10)) & "," & (testvarline(11)) & "," & (testvarline(12)) & "," & (testvarline(14)) & ")"
Debug.Print ITEMSQL
DoCmd.RunSQL ITEMSQL
DoCmd.SetWarnings False
DoCmd.Echo False
End If
Loop
Close #1
Depending upon the size of your file, it may not be possible to load it all into memory at once. If that is the case, you can split it into large chunks and do them one at a time.