How to get data from Excel and merge it into Word using MailMerge? - excel

Trying to get data from Excel and merge it into Word using MailMerge (just like how it is done in this video).
However, fields aren't getting updated after running this code. VBA isn't throwing any error so looks like code is fine. Can you please help?
Sub getdata()
Dim numRecord As Integer
Dim myName As String
myName = InputBox("Enter the field name and relax!")
Set dsMain = ActiveDocument.MailMerge.DataSource
If dsMain.FindRecord(FindText:=myName, Field:="Fields") = True Then
numRecord = dsMain.ActiveRecord
End If
End Sub
Note: Data in Excel looks like this:
Fields First Layer Second Layer
CC 5 3
So when someone enters CC in Input box I want first_layer and Second_layer fields in word to get updated to 5 and 3 respectiely.

If you're running the mailmerge from Word, you don't actually need any VBA for this - it can all be done with a SKIPIF field. For example the following field code does the same as the macro in the video is supposed to:
{SKIPIF{FILLIN "Name to merge" \o}<> {MERGEFIELD Name}}
or:
{SKIPIF{FILLIN "Name to merge" \o}<> «Name»}
Note: The field brace pairs (i.e. '{ }') for the above example are all created in the document itself, via Ctrl-F9 (Cmd-F9 on a Mac or, if you’re using a laptop, you might need to use Ctrl-Fn-F9); you can't simply type them or copy & paste them from this message. Nor is it practical to add them via any of the standard Word dialogues. Likewise, the chevrons (i.e. '« »') are part of the actual mergefields - which you can insert from the 'Insert Merge Field' dropdown (i.e. you can't type or copy & paste them from this message, either). The spaces represented in the field constructions are all required.

Related

Filter phone numbers from open text field - Power BI, excel, VBA

I have a text field in a table where I need to substitute phone numbers where applicable.
For example the text field could have:
Call me on 08588812885 immediately
Call me on 07525812845
I need assistance please contact me
Good service
Sometimes a phone number will be in the text but not always and the phone number entered will always be different.
Is there a measure to use to replace the phone numbers with no text.
Ideally the solution would be Power BI, but can also be done in the raw data using excel or VBA
Regular expression in VBA (excel) or Python (Power BI) is a straightforward solution.
I have never used PowerBI with Python before but manage to make following python script.
In PowerBI transformation steps I created a new column that would copy [message] columns and named it [noPhoneNumber], then next step ran this python script
import re
def removePhone(x):
return re.sub('\d{10,11}', "**number removed**", x)
length = len(dataset["noPhoneNumber"])
for iRow in range(length):
dataset["noPhoneNumber"][iRow] = removePhone(dataset["noPhoneNumber"][iRow])
so column "noPhoneNumber"
Call me on 08588812885 immediately
Call me on 07525812845
I need assistance please contact me
Good service
becomes
Call me on **number removed** immediately
Call me on **number removed**
I need assistance please contact me
Good service
In VBA Preferable create UDF (user defined function) and don't create a subroutine, that would be too error prone for this kind of problem.
[Added]
If you need to make a Excel based solution, you can create a UDF function like so:
(remember early binding to import of VBScript_RegExp_55.RegExp in excel)
Function removePhoneNumber(text As String, Optional replacement As String = "**number removed**") As String
Dim regex As New RegExp
regex.Pattern = "\d{10,11}"
removePhoneNumber = regex.Replace(text, replacement)
End Function
...and then use excel function like so:
=removePhoneNumber(A2),
=removePhoneNumber(A3)
and so on...
A simple VBA function alternative
Function removePhone(s As String) As String
Const DELIM As String = " "
Dim i As Long, tokens As Variant
tokens = Split(s, DELIM)
For i = LBound(tokens) To UBound(tokens)
If IsNumeric(tokens(i)) Then
tokens(i) = "*Removed*" ' << change to your needs
Exit For ' assuming a single phone number per string
End If
Next
removePhone = Join(tokens, DELIM)
End Function
You can do this in Power Query. Create a custom column with this below code. I have considered the column name is Comments but please adjust this with your column name.
if Text.Length(Text.Select([comments], {"0".."9"})) = 11
then
Text.Replace(
[comments],
Text.Select([comments], {"0".."9"}),
""
)
else [comments]
Here is the output below. You can also replace phone numbers with other text like #### to make is anonymous.
NOTE
This will only work if there are only 1 number in the string with length 11 (You can adjust the length in code as per requirement).
This will Not work if there are more than one Numbers in the string.
If there are 1 number in the string but length not equal 11, this will keep the whole string as original.

Error in saving minitab graphs and plots: "...collection is empty and contains no valid output object"

I want to automate GageR&R study in minitab.
I found code but the line mtbProject.Commands.Item(1).Outputs.Item(1).Graph.SaveAs.
Gives
Run time error:"IOutput: IOutput collection is empty and contains no valid output object"
Sub msa_macro()
'
' msa_macro Macro
'
'
Dim MtbApp As Mtb.Application
Dim mtbProject As Mtb.Project
Dim mtbWorksheet As Mtb.Worksheet
Set MtbApp = New Mtb.Application
Set mtbProject = MtbApp.ActiveProject
Set mtbWorksheet = mtbProject.ActiveWorksheet
MtbApp.UserInterface.Visible = True
MtbApp.UserInterface.DisplayAlerts = True
mtbProject.ExecuteCommand "Execute 'C:\Amir\DataAnalysis2\MSA_FixtureMill_STC049\MSA_STC049_BSM\Results_Files\readfileMinitab_test.mtb' 1."
mtbProject.Commands.Item(1).Outputs.Item(1).Graph.SaveAs "C:\Result_Files\grph1.png", True, GFJPEG
End Sub
The problem is, that you want to save the Outputs.Item(1) from Commands.Item(1). So you address the first command that you called, which is "Excecute … ", and this has no Output-Item. Therefore the IOutputs Collection for this Command-Item is empty.
The Output-Collection is defined as the Items of Outputs for each command. What you would want to do, is to save the first Output-Item of the command with which you created the graph.
It would be very helpful, if you could provide some information about your readfileMinitab_test.mtb. What are you doing in this .mtb file, is it also a macro-enabled file? I would guess, that you create the graph in this file?
If you want to save your graph as a .png, I guess you might need the MtbGraphFiletype GFPNGColor instead of GFJPEG. You also don´t need to save the file as grph1.png (just grph1 will suffice), as this is done automatically, because you tell Minitab to save it in a specific filetype.
You could also use the digit-code for the Filetypes (which is a little bit shorter). This would mean GFPNGColor = 3 and GFJPEG = 1. For some further information about this I recommend you the Minitab-Automation-Guide.
An example code could look as following:
'This is the first Command Minitab is executing
mtbProject.ExectueCommand "Execute <something>"
'This is the second Command Minitab is executing
mtbProject.ExecuteCommand "Boxplot C" & CStr(i as Integer)
'We want to Save the Graph, which we created with Command 2. We created one graph with
'this Command, to we only have 1 Output.
mtbProject.Commands.Item(2).Outputs.Item(1).Graph.SaveAs <path as String>, True, 3
Thanks Florian. Yes you are right, I figured it out that I am trying to read the output of the wrong command.
I wanted to execute a sequence of 'Gage R&R' commands and to save an output graph. It is completed now.
Thanks again for the helping answer.

Bolding multiple specific words based on a read in value in VBA

I am trying to bold specific words based on a string being read into vba code.
I have the string in read into vba and now want to pick out a word or words to bold them.
If the following was read into vba code: The boy ran down the street.
In the above sentence, what code would I use if I wanted to bold just the word boy? What would I use if I wanted to bold the words boy and the?
I have tried the following code but do not know how to modify it to my specific case.
https://code.adonline.id.au/vba-format-text-microsoft-word/
In short, I want code that will read in a string, search that string for x amount of words, and bold said words to be later exported.
Let me know if you need any more details and what I am trying to accomplish.
Excel is pretty good at formatting whole cells, but it's not very good at formatting parts of cells. One way that I've been able to do this is to turn the text into very basic HTML and then paste the text into a cell. Here's an example.
Public Sub BoldCertainWords()
Dim sSentence As String
Dim dobj As DataObject
Set dobj = New DataObject
sSentence = "The boy ran down the street"
sSentence = Replace$(sSentence, "boy", "<strong>boy</strong>")
sSentence = Replace$(sSentence, "the", "<strong>the</strong>")
dobj.SetText "<html>" & sSentence & "</html>"
dobj.PutInClipboard
Sheet1.Range("A1").Select
Sheet1.PasteSpecial "Unicode Text"
End Sub
You need to set a reference to the MS Forms 2.0 library to get the DataObject if you don't already have it.
Note also that case matters. This will bold the but not The. You could repeat for typical capitalization or get clever with how you find the words and build the HTML string.
Also note that this particular PastSpecial method is Worksheet method, not a Range method. You have to select the range first.

Excel VBA: How to write column name with commercial at "#" in it

I am trying to find out how I should deal with a named column in myTable which contains a commercial at (#) in its name, e.g. active # mail. This code is supposed to print the column number in the Immediate output window:
Sub teststring()
Dim s As String
s = ActiveSheet.Range("myTable[active # mail]").Column
Debug.Print s
End Sub
but it fails. Using .Range("myTable[active" & Chr(64) "& mail]") fails as well.
You can do it like this:
s = ActiveSheet.listobjects("myTable").listcolumns("active # mail").Range.Column
See also https://support.office.com/en-us/article/using-structured-references-with-excel-tables-f5ed2452-2337-4f71-bed3-c8ae6d2b276e for how to escape special characters
So:
s = ActiveSheet.Range("myTable[active '# mail]").Column
will also work.
# has a special meaning in structured references, so you can't use it in a column name without escaping it with ' (a single quote)

VBA Excel : Populate TextBox with specific string of text when Option Button is selected

I developed a Form in Excel (2016) and I am trying (with VBA) to configure its behavior so that if the user selects a particular option button, two additional things happen:
A checkbox further down on the form is automatically checked.
A text box further down on the form automatically displays a set string of text.
More specifically, if the user selects OptionButtonABC, then ...
CheckBoxNone should become checked
TextBoxCompanyName (which does not display any text by default) should now display the string: 'ABC'.
I initially created a subroutine that just targeted condition 1, and everything worked fine. However, when I try to integrate the code required to handle condition 2, things start to unravel.
Below, you will see the code in its most current state. I have a Private Sub that initiates upon the Click event and then immediately defines a variable as a string. I then set up an if/then statement that specifies what should happen IF OptionButtonABC is true. Namely, CheckBoxNone should be selected (this works fine) AND TextBoxCompanyName should now display the string 'ABC'.
Private Sub OptionButtonABC_Click()
Dim Variable_ABC As String
Variable_ABC = ABC
If Me.OptionButtonABC.Value = True Then
Me.CheckBoxNone = True And Me.TextBoxCompanyName.Text = Variable_ABC
End If
End Sub
The desired behavior should (theoretically) be pretty easy to achieve, but my experience with VBA is still pretty limited, so I am reaching out to the community for a bit of advice. As I mentioned above, the code above works for the first condition. However, I am still unable to get the string of text ('ABC') to show up in the text box.
Thanks in advance for any advice you may offer.
Private Sub OptionButtonABC_Click()
Dim Variable_ABC As String
Variable_ABC = "ABC" 'String Values uses double quotes
If Me.OptionButtonABC.Value = True Then
Me.CheckBoxNone = True
Me.TextBoxCompanyName.Text = Variable_ABC
End If
End Sub
The operator AND must be used only in the IF statement comparison, not in what you want to do.

Resources