I am trying to write an xml file ussing a little less conventional method, Just for those wondering there's a long story too why I am doing this. The real point is though that I cant seem to get the Tag named to write its value to the resulting XML file and I cant fuigureout why... could somebody help me with this...
The code as follows...
Private Sub SaveToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem2.Click
'define a save dialog
Dim save_file As New SaveFileDialog
'give its extension...
save_file.RestoreDirectory = True
save_file.InitialDirectory = My.Application.Info.DirectoryPath & " \ LIBRARY"
save_file.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"
save_file.FilterIndex = 1
''create a datatable
'Dim my_datatable As New DataTable
'if ok click
If save_file.ShowDialog() = DialogResult.OK Then
Using writer As New IO.StreamWriter(save_file.FileName)
writer.WriteLine("<COMPELATION>")
For Each row As DataGridViewRow In Me.DataGridView1.Rows
If Not row.IsNewRow Then
writer.WriteLine(String.Format(vbCrLf & vbTab & "<Data>" & vbCrLf & vbTab & vbTab & "<DEF>{0}</DEF>" & vbCrLf & vbTab & vbTab & "<HGT>{1}</HGT>" & vbCrLf & vbTab & vbTab & "<LEN>{2}</LEN>" & vbCrLf & vbTab & vbTab & "<WDT>{3}</WDT>" & vbCrLf & vbTab & vbTab & "<THK>{4}</THK>" & vbCrLf & vbTab & vbTab & "<AN1>{5}</AN1>" & vbCrLf & vbTab & vbTab & "<AN2>{6}</AN2>" & vbCrLf & vbTab & vbTab & "<MAT>{7}</MAT>" & vbCrLf & vbTab & "</Data>",
row.Cells(0).Value,
row.Cells(1).Value,
row.Cells(2).Value,
row.Cells(3).Value,
row.Cells(4).Value,
row.Cells(5).Value,
row.Cells(6).Value,
row.Cells(7).Value))
End If
Next
writer.WriteLine("</COMPELATION>")
writer.Close()
End Using
Dim result1 As DialogResult = MessageBox.Show("Would you like to use this file as the default library?", "Information", MessageBoxButtons.YesNo)
If result1 = DialogResult.Yes Then
'Set the new file as the default XML...
My.Settings.DEFAULTXML = save_file.FileName
'Reload and bind the data source...
Me.Refresh()
Else
End If
End If
End Sub
Related
I am trying to call a .bat file from VBA using: however I am getting Method Run of object IWshShell3 failed with the line in asteriks highlighted. I am not familiar with this error and don't know where to begin. I am running VB in excel 2010. Thank you :).
Dim PathCrnt As String
Dim wsh As Object
PathCrnt = ActiveWorkbook.Path & "\" & MyBarCode & "_" & MyScan
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
**wsh.Run "C:\Users\cmccabe\Desktop\NxClinical.bat", windowStyle, waitOnReturn**
End If
EDIT
The code runs but exits with error code 1. Basically, what I am trying to do is have the user enter a barcode and date, those values are used to change the directory to that. A batch file is called that runs a perl script on that directory. The batch file is not being called and I'm not sure why. 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" & vbTab & "SpikeIn Location" & vbTab & "Barcode"
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 & vbTab & ActiveSheet.Range("B20").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 & vbTab & ActiveSheet.Range("B20").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 & vbTab & ActiveSheet.Range("B20").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 & vbTab & ActiveSheet.Range("B20").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 perl
Dim PathCrnt As String
Dim Wsh As Object
Dim WaitOnReturn As Boolean
Dim WindowStyle As Integer
PathCrnt = MyDirectory
Set Wsh = VBA.CreateObject("WScript.Shell")
WaitOnReturn = True
WindowStyle = 1
Wsh.Run PathCrnt & "C:\Users\cmccabe\Desktop\NxClinical.bat", WindowStyle, WaitOnReturn
End If
Else
MsgBox "Nothing has been done. ", vbExclamation, "Goodbye!"
End If
Application.DisplayAlerts = False
Application.Quit
End Sub
Dim PathCrnt As String
Dim wsh As Object
PathCrnt = ActiveWorkbook.Path & "\" & MyBarCode & "_" & MyScan
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errrCode As Long
errrCode = wsh.Run( "cmd /C ""C:\Users\cmccabe\Desktop\NxClinical.bat""" _
, windowStyle, waitOnReturn)
If errrCode = 0 Then
MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errrCode & "."
End If
Note
explicitly run cmd /c;
enclose batch script (fully qualified) name in double quotes;
get (and treat) errrCode from called batch script.
If your batch script requires paramer(s), use them as follows (an example):
errrCode = wsh.Run( "cmd /C ""C:\Users\cmccabe\Desktop\NxClinical.bat"" par1 ""par 2""" _
, windowStyle, waitOnReturn)
Another example:
errrCode = wsh.Run( "cmd /C ""C:\Users\cmccabe\Desktop\NxClinical.bat"" " _
_ & """" & PathCrnt & """" , windowStyle, waitOnReturn)
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*\"
Guided by Jzz and David on another post, I discovered a VBA userform and modules that can be imported to Access DB or Excel that will ask you to select a file and it will display the EXIF external info of that file particularly GPS Longitude, Latitude, and Altitude.
My question is how do I convert this so it opens a folder instead and retrieves the GPS info on each of the files in that folder. I know it may need to loop through the contents of a folder but I have no idea how to convert this. Please see attached file and open it as Access DB. I was only able to transfer it to Excel but the code was written in too many extra calls and functions I couldn't understand right away. It would be nice to be able to modify it and make it shorter.
EXIFReader
Sarah
EDIT Thanks to David, here's my modified version:
Sub OpenFromFolder()
On Error GoTo ExifError
Dim strDump As String
'Dim fso As Scripting.FileSystemObject
'Dim fldr As Scripting.Folder
'Dim file As Scripting.file
Set fso = CreateObject("scripting.filesystemobject")
Set fldr = fso.GetFolder("C:/Users/JayP/Downloads/Camera Uploads/Pics") '#### Modify this to your folder location
For Each file In fldr.Files
'## ONLY USE JPG EXTENSION FILES!!
Select Case UCase(Right(file.Name, 3))
Case "JPG"
With GPSExifReader.OpenFile(file.Path)
currrow = Sheet1.UsedRange.Rows.Count + 1
Sheet1.Range("A" & currrow).Value = "GPSLatitudeDecimal: " & .GPSLatitudeDecimal
Sheet1.Range("B" & currrow).Value = "GPSLongitudeDecimal: " & .GPSLongitudeDecimal
Sheet1.Range("C" & currrow).Value = "GPSAltitudeDecimal: " & .GPSAltitudeDecimal
End With
End Select
NextFile:
Next
Exit Sub
ExifError:
MsgBox "An error has occurred with file: " & file.Name & vbCrLf & vbCrLf & Err.Description
Err.Clear
Resume NextFile
End Sub
That is fairly sophisticated code -- written by Wayne Phillips who is a certified Microsoft MVP. While it might be nice to make the code more human-readable, I suspect it is already quite optimized.
I am posting this answer because it's an interesting question/application, normally I would say "Show me what you have tried so far" but given the relative complexity of Wayne's code, I'll waive that requirement. HOWEVER the additional caveat is that I won't answer a dozen follow-up questions on this code to teach you how to use VBA. This code is tested and it works.
There is an unused function call that allows you to open from a path, we are going to use this in a loop, over the files in a specified folder.
Function OpenFile(ByVal FilePath As String) As GPSExifProperties
Set OpenFile = m_ClassFactory.OpenFile(FilePath)
End Function
1. Import the Class Modules from Wayne's code in to your workbook's VBProject (I think you have already done this).
2. Create a new subroutine like the one below, in a normal code module.
Sub OpenFromFolder()
On Error GoTo ExifError
Dim strDump As String
'## REQUIRES REFERENCE TO MICROSOFT SCRIPTING RUNTIME
Dim fso As Scripting.FileSystemObject
Dim fldr As Scripting.Folder
Dim file As Scripting.file
Set fso = CreateObject("scripting.filesystemobject")
Set fldr = fso.GetFolder("C:/users/david_zemens/desktop/") '#### Modify this to your folder location
For Each file In fldr.Files
'## ONLY USE JPG EXTENSION FILES!!
Select Case UCase(Right(file.Name, 3))
Case "JPG"
With GPSExifReader.OpenFile(file.Path)
strDump = strDump & "FilePath: " & .FilePath & vbCrLf
strDump = strDump & "DateTimeOriginal: " & .DateTimeOriginal & vbCrLf
strDump = strDump & "GPSVersionID: " & .GPSVersionID & vbCrLf
strDump = strDump & "GPSLatitudeDecimal: " & .GPSLatitudeDecimal & vbCrLf
strDump = strDump & "GPSLongitudeDecimal: " & .GPSLongitudeDecimal & vbCrLf
strDump = strDump & "GPSAltitudeDecimal: " & .GPSAltitudeDecimal & vbCrLf
strDump = strDump & "GPSSatellites: " & .GPSSatellites & vbCrLf
strDump = strDump & "GPSStatus: " & .GPSStatus & vbCrLf
strDump = strDump & "GPSMeasureMode: " & .GPSMeasureMode & vbCrLf
strDump = strDump & "GPSDOPDecimal: " & .GPSDOPDecimal & vbCrLf
strDump = strDump & "GPSSpeedRef: " & .GPSSpeedRef & vbCrLf
strDump = strDump & "GPSSpeedDecimal: " & .GPSSpeedDecimal & vbCrLf
strDump = strDump & "GPSTrackRef: " & .GPSTrackRef & vbCrLf
strDump = strDump & "GPSTrackDecimal: " & .GPSTrackDecimal & vbCrLf
strDump = strDump & "GPSImgDirectionRef: " & .GPSImgDirectionRef & vbCrLf
strDump = strDump & "GPSImgDirectionDecimal: " & .GPSImgDirectionDecimal & vbCrLf
strDump = strDump & "GPSMapDatum: " & .GPSMapDatum & vbCrLf
strDump = strDump & "GPSDestLatitudeDecimal: " & .GPSDestLatitudeDecimal & vbCrLf
strDump = strDump & "GPSDestLongitudeDecimal: " & .GPSDestLongitudeDecimal & vbCrLf
strDump = strDump & "GPSDestBearingRef: " & .GPSDestBearingRef & vbCrLf
strDump = strDump & "GPSDestBearingDecimal: " & .GPSDestBearingDecimal & vbCrLf
strDump = strDump & "GPSDestDistanceRef: " & .GPSDestDistanceRef & vbCrLf
strDump = strDump & "GPSDestDistanceDecimal: " & .GPSDestDistanceDecimal & vbCrLf
strDump = strDump & "GPSProcessingMethod: " & .GPSProcessingMethod & vbCrLf
strDump = strDump & "GPSAreaInformation: " & .GPSAreaInformation & vbCrLf
strDump = strDump & "GPSDateStamp: " & .GPSDateStamp & vbCrLf
strDump = strDump & "GPSTimeStamp: " & .GPSTimeStamp & vbCrLf
strDump = strDump & "GPSDifferentialCorrection: " & .GPSDifferentialCorrection & vbCrLf
Debug.Print strDump '## Modify this to print the results wherever you want them...
End With
End Select
NextFile:
Next
Exit Sub
ExifError:
MsgBox "An error has occurred with file: " & file.Name & vbCrLf & vbCrLf & Err.Description
Err.Clear
Resume NextFile
End Sub
You need to modify this:
Set fldr = fso.GetFolder("C:/users/david_zemens/desktop/")
And also this. I assume you already know how to put the data in a worksheet or display it on a form, etc. This line only prints to the console in the Immediate window of the VBA, it will not write to a worksheet/etc. unless you modify it to do so. That is not part of the question, so I will leave that up to you to work out :)
Debug.Print strDump
NOTE: I removed some object variables that you won't have in Excel, and added some new variables to do the Folder/Files iteration. I put in simple error handling to inform you of errors (msgbox) and resume the next file. In my testing, the only error I got was some files do not have EXIF data.
I have data in dataset which I am loopping to build up data for the email the data is as follows but I am using the following to produce the email using tabs but it doesnt see very iffiencet i can only use plain text is their a better way to get it to format nicer like using the datatable sizes or something
Dim dataForEmail As String = ""
Dim msg As String = ""
msg = "The Following Deliverys where processed for the Following Ordernumbers at " & DateTime.Now.ToString() & Chr(13)
dataForEmail = "Order Number" & vbTab & "BarCode" & vbTab & vbTab & vbTab & "Description" & vbTab & vbTab & vbTab & vbTab & vbTab & "Brand" & vbTab & vbTab & vbTab & "Size" & vbTab & "Colour" & vbTab & "Price" & vbTab & "RRP" & vbTab & vbTab & vbTab & "Qty" & Chr(13)
Dim totalcost As Decimal
If Not IsNothing(results) AndAlso Not IsNothing(results.Rows) _
AndAlso results.Rows.Count > 0 Then
For Each thisRow As DataRow In results.Rows
CreateDeliveryIncFileForGemini(thisRow)
totalcost = totalcost + thisRow.Item("RRPPrice")
dataForEmail = dataForEmail & BuildReportFoEmail(thisRow)
connection.ExecuteNonQuerySql(scriptBuilder.SetDeliveryStatus(2, 1, thisRow.Item("r3DeliveryId")))
Next
connection.ExecuteNonQuerySql(scriptBuilder.SetDeliveryStatus(1, 0))
dataForEmail = dataForEmail & vbCrLf & "Total Price " & totalcost.ToString()
SendEmailViaWebService(dataForEmail, cfb.EmailForDeliverys, cfb.FullNameForEmailSubject, msg)
End If
CloseConnection()
What i am trying to do is call functions from a string that I created
The example would be:
genoutput is a string I made to concatenate the function calls when a certain combo box item was selected...
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles Button2.Click
Select Case ComboBox1.SelectedItem
Case "First Name"
genoutput = genoutput & randomfirstname() & vbTab
Case "Last Name"
genoutput = genoutput & randomlastname() & vbTab
Case "Decimal"
genoutput = genoutput & gendecimal(CDbl(decimal1.text,decimal2.text)) & vbtab )
Case "Integer"
genoutput = (genoutput & geninteger(CInt(integer1.text,integer2.text)) & vbtab)
Case "Birthday"
genoutput = (genoutput & birthday(CInt(year1.text,year2.text)) & vbtab &)
End Select
I am trying to get a string that looks like this and runs
outfile.Write(randomfirstname() & vbTab & randomlastname() & vbTab & gendecimal(CDbl(decimal1.text,decimal2.text)) & vbTab & (CInt(integer1.text,integer2.text)) & vbTab & birthday(CInt(year1.text,year2.text)) & vbCrLf)
This will work if you remove the quotes from hello() & vbtab & goodbye(), but as JohnFx said, it seems like an unusual and unnecessary way to do it.
I think you might be looking for something more like:
1) ListBox1.Items.Add("Hello"), .Add("Goodbye"), ...
2) If ListBox1.ListIndex = 0 then call hello, else if ...