Sort lines by date (DD.MM.YYYY) - date

Is there a possibility to sort lines within a textfile by date and save the results to another output file? Each line begins with a date (DD.MM.YYYY). Delimiter between date and text is Tab (no space). I prefer a solution in VBS.
Source
25.11.1968 Death of Upton Sinclair
14.06.1946 Birthday Donald Trump
25.11.2016 Death of Fidel Castro
14.06.1969 Birthday Steffi Graf
01.01.2017 New Year
to the new order (target)
01.01.2017 New Year
14.06.1946 Birthday Donald Trump
14.06.1969 Birthday Steffi Graf
25.11.1968 Death of Upton Sinclair
25.11.2016 Death of Fidel Castro
Order to change and compare: Month-Day-Year

Here, it's not pretty and it doesn't sort in reverse order as you wanted, but hopefully this will teach you something if you learn like I do...
Option Explicit
Const fsoForReading = 1
Const fsoForWriting = 2
inputFile = "input.txt"
outputFile = "output.txt"
dim inputFile, outputFile, lineCount, file, fline, lDate, lYear, lMonth, lDay, iDate,output
dim a, d, i
dim objFSO, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
set a = CreateObject("System.Collections.ArrayList")
set d = CreateObject("Scripting.Dictionary")
'open up the file for reading
Set objFile = objFSO.GetFile(inputFile)
Set file = objFile.OpenAsTextStream(fsoForReading,-2)
Do Until file.AtEndOfStream
fline = file.ReadLine 'get the line
lDate = left(fline,10) 'get the date portion at the beginning (the first 10 characters)
lYear = split(lDate,".")(2) 'parse the year from the date
lMonth = split(lDate,".")(1) 'parse the month
lDay= split(lDate,".")(0) 'parse the day
iDate = lYear + lMonth + lDay 'put together the "index date". The date needs to be formatted as yyyymmdd so it is sortable
a.add iDate 'add the index date to an array for easier sorting
d.add iDate, fline 'add the index date and line contents to a dictionary object
Loop 'go to the next line in the file
a.Sort() 'sort the array of dates
for each i in a 'loop through the array of dates
output = output + d(i) + vbCrlf 'add the appropriate dictionary object to the output
Next
call writeFile(output) 'write the file
file.Close
WScript.Quit 0
sub writeFile(fc)
dim fso
'fn = fn + ".hl7"
Set fso = CreateObject("Scripting.FileSystemObject")
if (fso.FileExists(outputFile)) then
Set objFile = fso.OpenTextFile(outputFile,8,True)
objFile.writeline fc
objFile.Close
else
Set objFile = fso.CreateTextFile(outputFile,True)
objFile.writeline fc
objFile.Close
end if
end sub

Related

Macro for Saving Solidworks part configurations as dxf files

I have to save a lot of dxf files from Solidworks to use for a CNC machine.
I'm looking for help to create a macro to save each configuration of the part as the top view of a part as a .dxf in the same location as the Solidworks file is saved.
I have found two macros which I kind of need to be combined together.
The first one saves all configurations separately as part files
The second one saves a part as a dxf of the top view.
It would be much appreciated if anyone could help me
first macro:
' Macro created by Jeff Parker CSWP/MCP 12/30/02
'
' Rev.1 = Added completion message box. Also verified SolidWorks 2005 compatabliity.
'
' Rev.2 = Fixed macro for x64 bits machines (changed folder browse codes). Also verified SolidWorks 2014 compatabliity.
' (BY: Deepak Gupta www.gupta9665.com 07/26/14)
' Folder Browse Codes: http://www.cpearson.com/excel/browsefolder.aspx
'
' Rev.3 = Fixed macro for Weldment part configuration names having <As Machined> and <As Welded>. Also verified SolidWorks 2016 compatabliity.
' (BY: Deepak Gupta www.gupta9665.com 01/14/16)
'
' DISCLAIMER:
' * These macros are provided free of charge for personal use and/or reference.
' * These macros may be freely distributed, provided the original copyright
' notices remain unchanged and intact.
' * All macros were written to work with SolidWorks 2005.
' * These macros, and corresponding files, are provided as is.
' * There are no warranties, expressed or implied, that these macros will perform
' as indicated, perform to users expectations, or complete a specific task.
' * These macros will change the current SolidWorks document. Use these macros at
' your own risk. Back up your data before using this macro on any SolidWorks
' document.
'
' ******************************************************************************
Dim swApp As SldWorks.SldWorks
Dim Part As SldWorks.ModelDoc2
Dim boolstatus As Boolean
Dim longstatus As Long
Dim Annotation As Object
Dim Gtol As Object
Dim DatumTag As Object
Dim FeatureData As Object
Dim Feature As Object
Dim Component As Object
Dim ConfigNamesArray As Variant
Dim ConfigNameMain As Variant
Dim ConfigName As Variant
Dim NewName As String
Dim PartName As String
Dim OpenName As String
Dim CurrentConfigName As Variant
Dim fileerror As Long
Dim filewarning As Long
Dim OrigConfigName As Variant
Dim Location As Variant
Dim ModLoc As String
Dim MassProps As Variant
Dim Mass As Variant
Dim MassError As Long
Dim ConfigCount As Long
Dim MassPropArrayTest As Long
Dim CustomPropNamesArray As Variant
Dim CustomPropName As Variant
Dim PartSourceName As String
Dim PartSourcePath As String
Dim status As Boolean
Sub main()
Set swApp = Application.SldWorks 'Connect to SolidWorks session
Set Part = swApp.ActiveDoc 'Set Part variable to active doc
If Part Is Nothing Then Exit Sub
ConfigCount = Part.GetConfigurationCount 'Get number of configurations
PartSourceName = Part.GetTitle 'Get name of original part file that contains configurations
If Part.GetType <> swDocPART Then 'Check to see if current document is a part
MsgBox "Only Allowed on Parts, Please open a part and try again.", vbOKOnly, "Error" ' Display error message"
Exit Sub ' Exit this program
ElseIf ConfigCount = 1 Then
MsgBox "Must have at least two configurations before starting macro.", vbOKOnly, "Error" ' Display error message"
Exit Sub ' Exit this program
Else
GoTo Rip
End If
Rip: 'RIP sub section
frmLocation.Show 'Show form
Location = frmLocation.txtPath.Text 'Get user selected location
'---Check to see if location has last backslash---
ModLoc = Right(Location, 1)
If ModLoc <> "\" Then
Location = Location & "\"
End If
ConfigNamesArray = Part.GetConfigurationNames 'Populate the array with all config names
OrigConfigName = ConfigNamesArray(0) 'Get current configuration
For i = 0 To UBound(ConfigNamesArray)
ConfigName = ConfigNamesArray(i) 'Assign next config name to ConfigName variable
Part.ShowConfiguration2 (ConfigName) 'Set next config as current
ConfigName = Replace((Replace(ConfigName, "<As Machined>", "")), "<As Welded>", "")
NewName = Location & ConfigName & ".sldprt" 'Create path
Part.SaveAsSilent NewName, True 'Save as current config name
Next i
PartSourcePath = Part.GetPathName
swApp.CloseDoc PartSourceName 'Close the source file to conserve memory for program
Set Part = Nothing 'Clear part variable
For j = 0 To UBound(ConfigNamesArray)
ConfigNameMain = ConfigNamesArray(j) 'Populate ConfigNameMain with current name
ConfigNameMain = Replace((Replace(ConfigNameMain, "<As Machined>", "")), "<As Welded>", "")
OpenName = Location & ConfigNameMain & ".sldprt" 'Set location of file to open
fileerror = swFileNotFoundError 'Default system error message
filewarning = swFileSaveWarning_NeedsRebuild 'Default warning message
swApp.OpenDoc6 OpenName, 1, 0, "", fileerror, filewarning 'Open saved configuration file
Set Part = swApp.ActiveDoc 'Set newly opened file as current
Part.DeleteDesignTable 'Delete design table if present
For k = 0 To UBound(ConfigNamesArray) 'Delete all configurations from new file
ConfigName = ConfigNamesArray(k)
Part.DeleteConfiguration2 (ConfigName)
Next k
Part.EditConfiguration3 ConfigNameMain, "Default", "", "", 0 'Rename leftover config to default
Part.ViewZoomtofit2 'Make part zoom to fit so icon looks good
Part.Save2 (True) 'Save newly modified part
Set Part = Nothing 'Clear Part variable
swApp.CloseDoc ConfigNameMain & ".sldprt" 'Close current part
Next j
swApp.OpenDoc6 PartSourcePath, 1, 0, "", fileerror, filewarning 'Open original source file
Set Part = swApp.ActiveDoc 'Set original part as current
Part.ShowConfiguration2 (OrigConfigName) 'Set original part to original status
MsgBox "Here is where you can find your files: " & Chr(13) & Location, vbInformation, "Configuration Rip Success!"
Location = "" 'Clear location variable
End Sub 'Close program
second macro:
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swPart As SldWorks.PartDoc
Dim sModelName As String
Dim sPathName As String
Dim varAlignment As Variant
Dim dataAlignment(11) As Double
Dim varViews As Variant
Dim dataViews(0) As String
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swPart = swModel
sModelName = swModel.GetPathName
sPathName = Left(sModelName, Len(sModelName) - 6) & "dxf"
dataAlignment(0) = 0#
dataAlignment(1) = 0#
dataAlignment(2) = 0#
dataAlignment(3) = 1#
dataAlignment(4) = 0#
dataAlignment(5) = 0#
dataAlignment(6) = 0#
dataAlignment(7) = 0#
dataAlignment(8) = -1#
dataAlignment(9) = 0#
dataAlignment(10) = 1#
dataAlignment(11) = 0#
varAlignment = dataAlignment
dataViews(0) = "*Top"
varViews = dataViews
swPart.ExportToDWG2 sPathName, sModelName, swExportToDWG_e.swExportToDWG_ExportAnnotationViews, True, varAlignment, False, False, 0, varViews
End Sub
Try the following codes which exports each configuration of the active part as DXF.
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim sModelName As String
Dim sPathName As String
Dim vConfNameArr As Variant
Dim i As Long
Dim sConfigName As String
Dim bRebuild As Boolean
Dim swPart As SldWorks.PartDoc
Dim nFileName As String
Dim varAlignment As Variant
Dim dataAlignment(11) As Double
Dim varViews As Variant
Dim dataViews(0) As String
Sub Main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
' Is document active?
If swModel Is Nothing Then
swApp.SendMsgToUser2 "A Sheet Metal Part must be open.", swMbWarning, swMbOk
Exit Sub
End If
' Is it a part document?
If swModel.GetType <> SwConst.swDocPART Then
swApp.SendMsgToUser2 "A Sheet Metal Part must be open.", swMbWarning, swMbOk
Exit Sub
End If
sModelName = swModel.GetPathName
sPathName = Left(sModelName, InStrRev(sModelName, "\"))
vConfNameArr = swModel.GetConfigurationNames
For i = 0 To UBound(vConfNameArr)
sConfigName = vConfNameArr(i)
If Not UCase(sConfigName) Like "*FLAT*" Then
swModel.ShowConfiguration2 (sConfigName)
bRebuild = swModel.ForceRebuild3(False)
nFileName = sPathName & sConfigName & ".DXF"
Set swPart = swModel
dataAlignment(0) = 0#
dataAlignment(1) = 0#
dataAlignment(2) = 0#
dataAlignment(3) = 0#
dataAlignment(4) = 0#
dataAlignment(5) = 0#
dataAlignment(6) = 0#
dataAlignment(7) = 0#
dataAlignment(8) = 0#
dataAlignment(9) = 0#
dataAlignment(10) = 0#
dataAlignment(11) = 0#
varAlignment = dataAlignment
dataViews(0) = "*Top"
varViews = dataViews
'Export Top View
swPart.ExportToDWG2 nFileName, sModelName, 3, True, varAlignment, False, False, 0, varViews
End If
Next i
End Sub

Macro to pick file in folder with current date in other than standard format

Could you please let me know how to revise the below code so that it opens it automatically?
Range("A1:AK1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Range("A1").Select
Workbooks.Open Filename:= _
"Y:\DentalConsumables\Company\DMC\DMC - Planning & Materials\Build Plan DTW Reports\DataWHSreports\2015-03-26_DWHS_PEN EU Fixed.xlsx" _
, UpdateLinks:=0, Notify:=False
ActiveWindow.SmallScroll Down:=12
If only the date part changes, you can give this a try:
Edit1: Closing the opened file
Dim curDate As String, Fname As String
curDate = Format(Date, "yyyy-mm-dd") ' returns the current date in specified format
Dim wb As Workbook ' add a variable to pass your workbook object
Fname = "Y:\DentalConsumables\Company\DMC\DMC - Planning & Materials\" _
& "Build Plan DTW Reports\DataWHSreports\" & curDate
& "_DWHS_PEN EU Fixed.xlsx"
Set wb = Workbooks.Open(FileName:=Fname, UpdateLinks:=False, Notify:=False)
' ~~> Other cool stuff goes here
wb.Close False ' Close the opened workbook; False indicates to not save changes

Macro to find user input date range and delete everything outside range

Wondering if someone could help me in developing a simple user interfacing macro.
I have a set of data with the first Column (A) being dates. The date range can be an arbitrary range so could go from any start date to end date (most of the time its a 6/8 weeks). Lets say for arguments sake the date range goes from 31/12/2014 18:00 to 09/02/2015 18:00 (note date is UK format of dd/mm/yyyy). I would like the user to be asked for a start and end date range that they went - say 01/01/2015 to 31/01/2015. Once they have chosen the range the macro should delete everything BEFORE their selected date range (and shift cells up) and delete everything AFTER their selected date range. The date range is in increments of 10 minutes.
I've written some code to start off:
Public Sub DateRngInput()
Dim startDate As String
Dim endDate As String
Dim sRow As Long
Dim eRow As Long
Dim lastRow As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
startDate = Left(Worksheets("Template").Cells(1, 1), 10)
endDate = Left(Worksheets("Template").Cells(lastRow, 1), 10)
sDate = InputBox("Choose Start date (dd/mm/yyyy)" & vbNewLine & vbNewLine & "Data range starts at " & startDate)
eDate = InputBox("Choose End date (dd/mm/yyyy)" & vbNewLine & vbNewLine & "Data range ends at " & endDate)
'On Error Resume Next
sRow = Worksheets("Template").Range("$A$1:$A" & lastRow).Find(sDate, LookAt:=xlPart).Row
eRow = Worksheets("Template").Range("$A$1:$A" & lastRow).Find(eDate, SearchDirection:=xlPrevious, LookAt:=xlPart).Row
MsgBox ("Your date range is from: " & vbNewLine & sDate & " at Row " & sRow & vbNewLine & "To " & vbNewLine & eDate & " at Row " & eRow)
End Sub
The macro errors out at the following line with the Run-Time error '91':
sRow = Worksheets("Template").Range("$A$1:$A" & lastRow).Find(sDate, LookAt:=xlPart).Row
Any help would be much appreciated!
Thanks.
Say we have data like:
Notice the material is not even sorted! We wish to retain only data between 1 February 2015 and 15 February 2015.
We will loop from the bottom moving up. We delete all rows outside the date limits
Sub DateKleaner()
Dim early As Date, late As Date, N As Long
Dim dt As Date
early = DateSerial(2015, 2, 1)
late = DateSerial(2015, 2, 15)
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = N To 1 Step -1
dt = Cells(i, 1).Value
If dt > late Or dt < early Then
Cells(i, 1).EntireRow.Delete
End If
Next i
End Sub
We will be left with:
EDIT#1:
Here is some code which asks the User to supply the dates:
Sub DateKleaner()
Dim early As Date, late As Date, N As Long
Dim dt As Date
early = CDate(Application.InputBox(Prompt:="Please enter start date:", Type:=2))
late = CDate(Application.InputBox(Prompt:="Please enter end date:", Type:=2))
MsgBox early & vbCrLf & late
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = N To 1 Step -1
dt = Cells(i, 1).Value
If dt > late Or dt < early Then
Cells(i, 1).EntireRow.Delete
End If
Next i
End Sub
Naturally you would probably use your own UserForm to accomplish the same thing.

Loop subroutine for every used row using multiple dynamic cell references

Basically what I am trying to do is, sending an email for every used row on the target worksheet, each row has the details of the addresses, subject line, table with values etc.
So I can't seem to get it working, as it only dispatches one email from the first target row (2nd row).
I have tried using a combination of For Each and For i = 1 to LR which aren't working. I suspect it is to do with the cell references.
Here is the code:
Sub TestEmail1()
Application.ScreenUpdating = False
Dim aOutlook As Object
Dim aEmail As Object
Dim rngeAddresses As Range, rngeCell As Range, strRecipients As String
Dim ccAddresses As Range, ccCell As Range, ccRecipients As String
Dim rngeSubject As Range, SubjectCell As Range, SubjectContent As Variant
Dim rngeBody As Range, bodyCell As Range, bodyContent As Variant
Dim Table1 As Range
Dim i As Integer
For Each c In ActiveSheet.UsedRange.Columns("A").Cells
Set rng = ActiveSheet.UsedRange
LRow = rng.Rows.Count
For i = 2 To LRow
Set Table1 = Worksheets(1).Range("K1:R1")
Set Table2 = Worksheets(2).Range("K" & i & ":" & "R" & i)
Set aOutlook = CreateObject("Outlook.Application")
Set aEmail = aOutlook.CreateItem(0)
'set sheet to find address for e-mails as I have several people to
'mail to
Set rngeAddresses = ActiveSheet.Range("B" & i)
For Each rngeCell In rngeAddresses.Cells
strRecipients = strRecipients & ";" & rngeCell.Value
Next
Set ccAddresses = ActiveSheet.Range("C" & i)
For Each ccCell In ccAddresses.Cells
ccRecipients = ccRecipients & ";" & ccCell.Value
Next
Set rngeSubject = ActiveSheet.Range("D" & i)
For Each SubjectCell In rngeSubject.Cells
SubjectContent = SubjectContent & SubjectCell.Value
Next
Set rngeBody = ActiveSheet.Range("E" & i)
For Each bodyCell In rngeBody.Cells
bodyContent = bodyContent & bodyCell.Value
Next
'set Importance
'aEmail.Importance = 2
'Set Subject
aEmail.Subject = rngeSubject
'Set Body for mail
'aEmail.Body = bodyContent
aEmail.HTMLBody = bodyContent & "<br><br><br>" & RangetoHTML_ (Table1)
aEmail.To = strRecipients
aEmail.CC = ccRecipients
aEmail.Send
Exit Sub
Next i
Next c
End Sub
There is an Exit Sub at the end of your inner loop that makes the code exit from the procedure after the first iteration:
Sub TestEmail1()
...
For Each c In ActiveSheet.UsedRange.Columns("A").Cells
...
For i = 2 To LRow
...
Exit Sub
Next i
Next c
End Sub
Remove it and processing should continue as desired.

When exporting Word review comments, how do you reference the sentence related to a comment?

I am trying to export a Word document's review comments. I want to export the sentence selection that was commented on followed by the comment.
Screen shot of the image: http://jspeaks.com/mswordcomment.png
I have found code to loop through the document comments, but I cannot figure out how to reference the sentence selection that the comment was related to.
The current logic is:
Sub ExportComments()
Dim s As String
Dim cmt As Word.Comment
Dim doc As Word.Document
For Each cmt In ActiveDocument.Comments
s = s & cmt.Initial & cmt.Index & "," & cmt.Range.Text & vbCr
Next
Set doc = Documents.Add
doc.Range.Text = s
End Sub
I tinkered with Selection.Range, however I cannot determine the proper object or property that contains the referenced sentence.
I would like to produce output like the following (if we use the example in picture above):
Sentence: Here are more sentences that contain interesting facts - Comment: This is an interesting fact.
Sentence: Here are more sentences that contain interesting facts. Here are more sentences that contain interesting facts. - Comment: This is a very interesting fact
I found someone on another site to solve this question.
The key to the solution is: cmt.Scope.FormattedText
Here is the function revised:
Sub ExportComments()
Dim s As String
Dim cmt As Word.Comment
Dim doc As Word.Document
For Each cmt In ActiveDocument.Comments
s = s & "Text: " & cmt.Scope.FormattedText & " -> "
s = s & "Comments: " & cmt.Initial & cmt.Index & ":" & cmt.Range.Text & vbCr
Next
Set doc = Documents.Add
doc.Range.Text = s
End Sub
I have gathered several pieces of code and came to this solution:
Sub CopyCommentsToExcel()
'Create in Word vba
'TODO: set a reference to the Excel object library (Tools --> Reference --> Microsoft Excel 12.0 Object library)
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim i As Integer
Dim HeadingRow As Integer
HeadingRow = 3
Dim cmtRef As Range
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWB = xlApp.Workbooks.Add ' create a new workbook
With xlWB.Worksheets(1)
' Create report info
.Cells(1, 1).Formula = "Reviewed document:"
' Create Heading
.Cells(HeadingRow, 1).Formula = "Index"
.Cells(HeadingRow, 2).Formula = "Page"
.Cells(HeadingRow, 3).Formula = "Line"
.Cells(HeadingRow, 4).Formula = "Comment"
.Cells(HeadingRow, 5).Formula = "Reviewer"
.Cells(HeadingRow, 6).Formula = "Date"
For i = 1 To ActiveDocument.Comments.Count
.Cells(2, 1).Formula = ActiveDocument.Comments(i).Parent
.Cells(i + HeadingRow, 1).Formula = ActiveDocument.Comments(i).Index
.Cells(i + HeadingRow, 2).Formula = ActiveDocument.Comments(i).Reference.Information(wdActiveEndAdjustedPageNumber)
.Cells(i + HeadingRow, 3).Formula = ActiveDocument.Comments(i).Reference.Information(wdFirstCharacterLineNumber)
.Cells(i + HeadingRow, 4).Formula = ActiveDocument.Comments(i).Range
.Cells(i + HeadingRow, 5).Formula = ActiveDocument.Comments(i).Initial
.Cells(i + HeadingRow, 6).Formula = Format(ActiveDocument.Comments(i).Date, "dd/MM/yyyy")
' .Cells(i + 1, 3).Formula = ActiveDocument.Comments(i).Parent
' .Cells(i + 1, 3).Formula = ActiveDocument.Comments(i).Application
' .Cells(i + 1, 7).Formula = ActiveDocument.Comments(i).Author
Next i
End With
Set xlWB = Nothing
Set xlApp = Nothing
End Sub
Most valuable help from Microsoft Answers