Software Requirements Reviews with MS Word - How do I get metrics in an automated way? - requirements

Let's say I have a requirements document in MS Word, and someone else reviews it an provides a list of issues found using the "Track Changes" feature.
Is there a way to extract "how many major/minor issues were found during the review?" using an automated script - for metrics purposes?
I see CodeCollaborator has some MS Word integration, but it doesn't seem to know how to look inside Word to extract the tracked changes data. It just launches the document.

I did once write a Word macro that extracts the comments to a separate document, you are welcome to try adapting this to your purposes, if you have trouble then reply here and I can give you a hand with making changes.
Public Sub PROCESS_COMMENTS()
Dim strReplaceText As String
Dim myPar As Paragraph
Dim strCurrentColumn As String
Dim i As Integer
Dim Com As Comment
Application.ScreenUpdating = False
' set the input and output docs.
Set inDoc = ActiveDocument
' check we have comments to process in the original document
If inDoc.Comments.Count < 1 Then
MsgBox "No comments in the document"
Exit Sub
End If
' comments exist so create new document
Set outDoc = Documents.Add
Set outRange = outDoc.Content
outDoc.Range.InsertAfter "List of Comments:"
outDoc.Paragraphs(outDoc.Paragraphs.Count).Style = outDoc.Styles("Heading 1")
outDoc.Range.InsertParagraphAfter
' cycle through comments, inserting them in the new document
' display the new document and refresh
outDoc.Activate
Application.ScreenRefresh
For Each Com In inDoc.Comments
outRange.InsertAfter "[" & Com.Author & " - " & Com.Initial & Com.Index & "] "
outDoc.Paragraphs(outDoc.Paragraphs.Count).Range.Font.Bold = True
outDoc.Range.InsertParagraphAfter
outRange.InsertAfter Com.Range.Text
outDoc.Paragraphs(outDoc.Paragraphs.Count).Range.Font.Bold = False
Set myRange = Com.Scope
outDoc.Range.InsertParagraphAfter
outDoc.Range.InsertParagraphAfter
Next
Application.ScreenUpdating = True
Set outDoc = ActiveDocument
End Sub

Related

Access Code partially stopped working (not populating data to word document)

I have an Access database with linked tables. I have created a code to do the following:
1- Create a folder in a specific location with a specific name (name populated from data in access).
2- Open a word document saved in a specific path
3- I then use formfields in the document to populate the word document with data from the table
4- Lastly, I save the word document to the previously created folder with a new name using data from the table
I have been using this code successfully for well over a year with no issues.
Suddenly, for no apparent reason and without any change to the code it stopped populating the word document with data. note, its still doing steps 1,2, & 4 but not step 3.
I cannot figure out what the issue is and any help would be much appreciated.
Below is a sample of the code used:
Sub Onboarding_Documents_Saudi_Click()
'STEP ONE: create the appropriate Folder
Dim fs, cf, strFolder
On Error Resume Next
strFolder = "C:\Users\1161\OneDrive - Anfas Medical Care\Master - Anfas Medical Care\New Employees\" & Me.Name_In_English & " " & Me.Emp_Id
Set fs = CreateObject("Scripting.FileSystemObject")
If fs.FolderExists(strFolder) = True Then
MsgBox "'" & strFolder & "' already exists!"
Else
Set cf = fs.CreateFolder(strFolder)
If fs.FolderExists(strFolder) = True Then
MsgBox "'" & strFolder & "' successfully created!"
Else
MsgBox "'" & strFolder & "' was not successfully created!"
End If
End If
'STEP TWO:Make Contract .
Dim appWord As Word.Application
Dim doc As Word.Document
Dim Base As String
Base = Format(Me.base_salary, "Standard")
Dim Housing As String
Housing = Format(Me.housing_allowence, "Standard")
Dim Trans As String
Trans = Format(Me.transportation_allowence, "Standard")
On Error Resume Next
Err.Clear
Set appWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set appWord = New Word.Application
End If
Set doc = appWord.Documents.Open("C:\Users\1161\OneDrive - Anfas Medical Care\Master - Anfas Medical Care\Forms\Onboarding Documents\Access\Saudi\ContractSaudiAccess.docx", , True)
With doc
.FormFields("frnameinarabic").Result = Me.Name_In_Arabic
.FormFields("frnameinenglish").Result = Me.Name_In_English
.FormFields("frid").Result = Me.Document_ID_number
.FormFields("frmobile").Result = Me.mobile_number
.FormFields("frjtenglish").Result = Me.Job_title_English
.FormFields("frjtarabic").Result = Me.Job_Title_Arabic
.FormFields("frbasesalary").Result = Base
.FormFields("frhousing").Result = Housing
.FormFields("frtrans").Result = Trans
.FormFields("fremail").Result = Me.Personal_Email
.FormFields("empid").Result = Me.Emp_Id
.FormFields("joindate").Result = Me.Join_Date
.FormFields("joindatehijri").Result = Me.[Join Date Hijri]
.FormFields("contractperiod").Result = Me.[Contract Length]
.FormFields("contractperiodar").Result = Me.[Contract Length Ar]
.FormFields("frdepartment").Result = Me.Department
.FormFields("frdepartmentarabic").Result = Me.Department_Ar
.FormFields("joindate1").Result = Format(Me.Join_Date, "dddd dd/mmm/yyyy", vbUseSystemDayOfWeek)
.Activate
.Visible = True
.Activate
End With
doc.Fields.Update
doc.SaveAs2 "C:\Users\1161\OneDrive - Anfas Medical Care\Master - Anfas Medical Care\New Employees\" & Me.Name_In_English & " " & Me.Emp_Id & "\" & FileName & "Contract " & Me.Name_In_English & " " & Me.Emp_Id & ".docx"
Set doc = Nothing
Set appWord = Nothing```
Could this be a change due to Office Updates? I have something similar which works with Word v1910 (Build 12130.20272) but not in v2301 (Build 16026.20146). That may explain the second machine suddenly not working also?
It appears opening the "template" document which you are then adding information into opens read only as requested but now no longer allows changes to be made, which is where I think your code is skipping too? Our running code displays the Word document after filling in the form fields and there is no option to change the file mode to the top right of the screen to allow editing.
Screen shot of viewing / editing options from Word toolbar
I don't have an answer as to how to fix it as yet, I'm afraid, apart from making the template document open for write access and changing rights on the network to make the documents read only. We've not tested that as yet though. Hopefully it helps by giving you something else to check as the code has run successfully for a time and suddenly stopped.
I'm currently trying to find an option for opening a file as read only but allowing changes to the open document but am struggling to find anything like this in the Microsoft documentation. If I do find a solution I'll come back and post it.
It may work for you changing the following line from True to False at the end if the file is somewhere not shared.
Set doc = appWord.Documents.Open("C:\Users\1161\OneDrive - Anfas Medical Care\Master - Anfas Medical Care\Forms\Onboarding Documents\Access\Saudi\ContractSaudiAccess.docx", , True)

Insert an image file in a MAC Word Userform

I am not a programmer so not sure what to do here. I would like an option of adding an image file in a Microsoft Word document userform for MAC. I had used a code earlier which works perfectly in Windows but it doesnt work for MAC and gives a 5948 error. I had added a field for the image in the userform with a button to add the image and the final submit button. The add button should allow the user to insert any size image from the local folder.
The code I was using is given below:
Dim ImagePath As String
Private Sub CMDAddImage_Click()
Dim objFileDialog As Office.FileDialog
Set objFileDialog = Application.FileDialog(MsoFileDialogType.msoFileDialogFilePicker)
With objFileDialog
.AllowMultiSelect = False
.ButtonName = "File Picker"
.Title = "File Picker"
If (.Show > 0) Then
End If
If (.SelectedItems.Count > 0) Then
Call MsgBox(.SelectedItems(1))
ImagePath = .SelectedItems(1)
End If
End With
Image1.Picture = LoadPicture(ImagePath)
End Sub
And the code in submit button was:
Dim objWord
Dim objDoc
Dim objShapes
Dim objSelection
'Set objSelection = ActiveDocument.Sections
'objSelection.TypeText (vbCrLf & "One Picture will be inserted here....")
ActiveDocument.Bookmarks("Field04").Select
Set objShapes = ActiveDocument.InlineShapes
objShapes.AddPicture (ImagePath)
End
End Sub
Can someone please help me edit the code for mac. In mac it does not allow to add the file.
You should check out the suggestion made by #JohnKorchok in a comment to your previous question - insert an image Content Control in your document instead, and throw away the VBA.
But if you need to keep using VBA and a UserForm...
Application.FileDialog is not available on Mac.
Application.GetOpenFileName is not avaialble from Word (it's an Excel thing).
Application.Dialogs does not do the same thing as GetOpenFileName so the user experience will be rather different, but at its simplest, you can use it like this:
With Application.Dialogs(wdDialogFileOpen)
' .Display = -1 for "OK" ("Open" in this case)
' .Display = 0 for "Cancel"
' (THere are other possible return values
' but I do not think they are applicable here)
If .Display = -1 Then
ImagePath = .Name
End If
End With
or if you prefer, the lengthier
Dim dlg As Word.Dialog
Set dlg = Application.Dialogs(wdDialogFileOpen)
With dlg
If .Display = -1 Then
ImagePath = .Name
End If
End With
Set dlg = Nothing
However, this dilaog does not let you specify file types or any kind of filtering, a starting folder etc. Attempts to set Finder search criteria via something like
.Name = "(_kMDItemFileName = ""*.jpg"")"
.Update
before the .Display either can't work or need different syntax.
Further, the Apple dialog may start with its
own filtering set up so the user will have to click Options to enable All Files. You don't know what file type the user will choose so you will need to deal with that.
An alternative is to invoke Applescript. For this, it appears that you can still use the VBA MacScript command, which means that you can put all the script in your VBA file. If that does not work, then unfortunately you have to use AppleScriptTask which would require you to work some more on the Script and install the script in the correct folder on every Mac where you need this feature.
Here's the code I used - you would probably need to wrap everything up in another function call and use conditional compilation or other tests to call the correct routine depending on whether the code is running on Mac or Windows
Private Sub CMDAddImage_Click()
Dim s As String
Dim sFileName As String
On Error Resume Next
s = ""
' set this to some other location as appropriate
s = s & "set thePictureFoldersPath to (path to pictures folder)" & vbNewLine
s = s & "set applescript's text item delimiters to "",""" & vbNewLine
s = s & "set theFile to ¬" & vbNewLine
' add the image file types you want here
s = s & "(choose file of type {""png"",""jpg""} ¬" & vbNewLine
s = s & "with prompt ""Choose an image to insert."" ¬" & vbNewLine
s = s & "default location alias thePictureFoldersPath ¬" & vbNewLine
s = s & "multiple selections allowed false) as string" & vbNewLine
s = s & "set applescript's text item delimiters to """"" & vbNewLine
' choose file gives as an AFS path name (with colon delimiters)
' get one Word 2016/2019 will work with
s = s & "posix path of theFile"
sFileName = MacScript(s)
If sFileName <> "" Then
' Maybe do some more validation here
ImagePath = sFileName
Image1.Picture = LoadPicture(ImagePath)
End If
End Sub

Automatisation of macros

I have a Word document and I want to do following with it:
Select some part of it when I open a Word doc (let´s say from page 40 to 45).
Reverse text in selected area.
Get text reversed again as it was before opening, when I close document.
I have this code, that reverses the text:
Sub ReverseSelectedWords()
Dim i As Integer
Dim oWords As Words
Dim oWord As Range
Set oWords = Selection.Range.Words
For i = 1 To oWords.Count Step 1
Set oWord = oWords(i)
Do While oWord.Characters.Last.Text = " "
Call oWord.MoveEnd(WdUnits.wdCharacter, -1)
Loop
Debug.Print "'" & oWord.Text & "'"
oWord.Text = StrReverse(oWord.Text)
Next i
End Sub
For what you've described as being your goal, it would make far more sense to apply a password for opening to the document and provide only the intended reader(s) with that password. No code required.

Bug in MS Word's VBA Document Collection, not sure why this workaround crashes

MS Word 2010 has a bug in its ability to correctly maintain (of all things) the documents collection (link to earliest report found - social.msdn.microsoft.com).
As far as I can tell this bug only impacts Word 2010. Although the documents collection is not maintained, it turns out that the Application.Windows collection is. Hence, for Word 2010 the following code based on the original reporters investigation (see below) and this question on answers.microsoft.com seem to provide a good alternative to the buggy documents collection:
' PURPOSE:
' Return a document collection, work-around for Word 2010 bug
Public Function docCollection() As VBA.Collection
Dim indexOfAvailableAppWindows As Long
Dim resultDoc As VBA.Collection
Dim foundDoc As Word.Document
Set resultDoc = New Collection
For indexOfAvailableAppWindows = 1 To Application.Windows.Count
If Application.Windows(indexOfAvailableAppWindows).Document.Type = wdTypeDocument Then
Set foundDoc = Application.Windows(indexOfAvailableAppWindows).Document
resultDoc.Add foundDoc, foundDoc.FullName ' Can NOT use 'name' - fails to be unique
End If
Next indexOfAvailableAppWindows
Set docCollection = resultDoc
Set resultDoc = Nothing
End Function
However, and here's my question, the above code some times fails with error 457 This key is already associated with an element of this collection on line resultDoc.Add foundDoc, foundDoc.FullName. What circumstances could possibly lead to such a failure?
So far the code has only failed on 1 PC running Word 2016. I don't have access to the PC. I did discover that the original version used Document.Name as the key (which was not always unique, so this was changed to Document.Full name)
Assumptions:
Document.FullName will always be unique
Things I've ruled out:
use of Split Window
opening downloaded documents (protected window documents are not counted)
Code that can be used to demonstrate the issue in Word 2010 (adapted from the original report).
' Function Credit Bas258 (https://social.msdn.microsoft.com/profile/bas258)
Function test01() As Boolean
'Adapted to VBA from original: 03-11-2012 1.0 Visual Studio 2008 VB code
Dim oDoc As Word.Document
Dim oDoc0 As Word.Document
Dim oDoc1 As Word.Document
Dim oDoc2 As Word.Document
Dim oDoc3 As Word.Document
Dim oDoc4 As Word.Document
Dim n As Integer
Set WDapp = Application
With WDapp
Debug.Print (Format(Now(), "dd-MM-yyyy") & " MS Office " & .Application.Version)
Set oDoc0 = .Documents.Add: Debug.Print ("add " & oDoc0.Name)
Set oDoc1 = .Documents.Add: Debug.Print ("add " & oDoc1.Name)
Set oDoc2 = .Documents.Add: Debug.Print ("add " & oDoc2.Name)
Set oDoc3 = .Documents.Add: Debug.Print ("add " & oDoc3.Name)
Set oDoc4 = .Documents.Add: Debug.Print ("add " & oDoc4.Name)
For n = 1 To .Documents.Count
Debug.Print ("count " & n & " " & .Documents(n).Name)
Next n
Debug.Print ("close " & oDoc4.Name)
oDoc4.Close
Set oDoc4 = Nothing
Debug.Print ("close " & oDoc3.Name)
oDoc3.Close
Set oDoc3 = Nothing
For n = 1 To .Documents.Count
Debug.Print ("count " & n & " " & .Documents(n).Name)
Next n
n = 0
For Each oDoc In .Documents
n = n + 1
Debug.Print ("doc " & n & " " & oDoc.Name)
Next oDoc
n = 0
For Each oWin In .Windows
n = n + 1
Debug.Print ("win " & n & " " & oWin.Document.Name)
Next oWin
Debug.Print ("close " & oDoc2.Name)
oDoc2.Close
Set oDoc2 = Nothing
Debug.Print ("close " & oDoc1.Name)
oDoc1.Close
Set oDoc1 = Nothing
Debug.Print ("close " & oDoc0.Name)
oDoc0.Close
Set oDoc0 = Nothing
End With
Set WDapp = Nothing
End Function
This is NOT going to be the accepted answer. Although it does answer the broader question (what could cause this code to crash) it not address the specific crash that I am trying to isolate. Either way there appears to be another bug in MS Word which seemed to be worth capturing for the common good.
This time the bug is with the Windows Collection; and joy of joys, I've confirmed it for both Word 2010 and Word 2016 - both 64 bit apps.
Steps to reproduce the bug are as follows:
In windows explorer enable the Preview Pane
Select a word document FILE so that it is 'previewed'
Open the same document (without losing the 'preview view')
Run the code from the OP, it will crash on this line:
If Application.Windows(indexOfAvailableAppWindows).Document.Type = wdTypeDocument Then
It turns out that when a word file is being previewed the Application.Windows.Count property is incremented by the preview; however any attempt to get a property of that window results in Error 5097 - Word has encountered a problem.
So, an improvement to the original code would therefore be:
' PURPOSE:
' Returns a healthy document collection
' - work-around for Word 2010 bug
' - excludes hits from Windows Explorer Preview Pane
Public Function docCollection() As VBA.Collection
On Error GoTo docCollectionError
Dim indexOfAvailableAppWindows As Long
Dim resultDoc As VBA.Collection
Dim foundDoc As Word.Document
Set resultDoc = New Collection
' Use index instead of Each to avoid For Loop Not initialised error, preview pane
For indexOfAvailableAppWindows = 1 To Application.Windows.Count
If Application.Windows(indexOfAvailableAppWindows).Document.Type = wdTypeDocument Then
Set foundDoc = Application.Windows(indexOfAvailableAppWindows).Document
resultDoc.Add foundDoc, foundDoc.FullName ' Key must NOT be 'name' - fails to be unique see BUG: 1315
End If
lblSkipThisDoc:
Next indexOfAvailableAppWindows
Set docCollection = resultDoc
Set resultDoc = Nothing
Exit:
Exit Function
docCollectionError:
If Err.Number = 5097 Then ' An open document is also open in the Windows Explorer Preview Pane
Err.Clear
Resume lblSkipThisDoc ' - skip this window
End If
If Err.Number = 457 Then ' Key is already used, but HOW? Unknown cause of error
Err.Clear
Stop 'Resume lblSkipThisDoc ' Is it safe to skip this document, why is there a duplicate?
End If
End Function
There is a setting in MS Word that enables 1 document to be viewed in 2 windows. In Word 2010 it is under the View (Tab): Window > New Window
The new window is counted separately in Application.Windows.Count and returns the same document object, hence the key exists.
For indexOfAvailableAppWindows = 1 To Application.Windows.Count ' <<< New Windows is counted
If Application.Windows(indexOfAvailableAppWindows).Document.Type = wdTypeDocument Then
Set foundDoc = Application.Windows(indexOfAvailableAppWindows).Document
resultDoc.Add foundDoc, foundDoc.FullName ' <<< fails to add 2nd instance of document
End If
So... the solution would likely involve checking the caption of the document:
IMMEDIATE WINDOW:
?foundDoc.Windows(1).Caption
Document2:1

Change display text of all hyperlinks in document

Im pretty much void of visual basic knowledge but I know this can be done some how.
I have a 144 page document where I need to have the url be displayed.
For example: where an inserted link displaying "Google" will now display: "Google (www.google.com)"
There are some 200+ links in this document (originally was suppose to just be an electronic document) but now need to have it so that if someone had a printed copy in hand they would know the URL. I'm open to all sorts of ideas :(
One thought I had was to do Alt F9 to view the field codes and then somehow do a find replace and input some sort of code to have the display text and the url show?
Earlier I had someone who had some visual basic knowledge trying to help with who found this which I couldn't get to run for me... Is it my lack of understanding on how to make it run?
'Private Declare Function GetTickCount Lib "kernel32" () As Long
Public Sub GetHyperlinks()
Dim myDoc As Document
Dim wombat As Hyperlink
' Dim starttime As Long
Dim CurrentDoc As Document
Applicationhttp://images.intellitxt.com/ast/adTypes/icon1.png.ScreenUpdating = False
Set CurrentDoc = ActiveDocument
Set myDoc = Application.Documents.Add()
' starttime = GetTickCount
For Each wombat In CurrentDoc.Hyperlinks
myDoc.Range.InsertAfter wombat.TextToDisplay & vbTab & wombat.Address & vbCrLf
Next
' Debug.Print GetTickCount - starttime
Application.ScreenUpdating = True
myDoc.Range.ParagraphFormat.TabStops.Add CentimetersToPoints(7.5), wdAlignTabLeft, wdTabLeaderSpaces 'basic formatting
End Sub
This should work for you (tested in Word 2010):
Sub UpdateDocLinks()
Dim link As Hyperlink
For Each link In ActiveDocument.Hyperlinks
link.TextToDisplay = link.TextToDisplay & " (" & link.Address & ")"
Next link
End Sub
This will append the URL in parenthesis to every active hyperlink in the document:
Google becomes Google (http://www.google.com)