Allowing user to select text in word vba macro - vba

In VBA for Word 2007, I want to be able to open a document, highlight sections of text and replace those sections with fields linked to a docvariables. The process would be:
Open document.
Select text.
Select docvariable from list.
Insert field linked to selected docvariable.
Repeat steps 1-4 as required.
There is no way to know beforehand what the text to be selected is or which docvariable is going to be linked to which field or how many times these steps are going to be repeated.
Only with Microsoft could the most absolutely fundamental, simple task of allowing the user to make a selection at run-time and pass this selection back to sub-routine be so tortuous and surreal. I have spent 2 days trying to figure this out. If anyone can help, I will name my next child after you.

I think "tortuous and surreal" is a misconception.
Create a small form with a dropdown (named "selVarName", for example) that lets you select all document variable names available. Link the form to a custom button in the Quick Access Toolbar.
Upon clicking "OK" in this form do something like this:
Private Sub btnOK_Click()
Dim v As Word.Variable
Dim n As String
n = Me.selVarName.Value
With Selection
For Each v In .Document.Variables
If v.Name = n Then v.Delete: Exit For
Next v
.Document.Variables.Add n, .Range.Text
End With
End Sub
And this has bells and whistles already. You can do additional checking like "no text selected", for example.

Related

Search text file and put matching results in listbox

I have a VB.NET project in which there is a form where there is a TextBox control, a ListBox control and an external text file that contains a list of outlook folder paths for client emails.
Essentially, the user enters into the text box the name of a client and/or their unique reference number, presses the search button (yes - I know I could make the results appear as they type, I want a button!) and it comes up with the matching results for the company name or serial number that are in the text file and puts them in the list box, with the full path of the outlook email folder.
For example:
If I put into the textbox: "06967759-274D-40B2-A3EB-D7F9E73727D7"
It would put the following result into the listbox:
"EIS Admin\Contacts{06967759-274D-40B2-A3EB-D7F9E73727D7}"
And the user can then go to that folder and find the email(s).
I have gone through several revisions both of my own code and code pasted from online with people having the same issue, only to have Visual Studio throw no errors, run the code and have no luck, with it doing nothing but clearing the list box, and not showing matching results of any kind.
I understand this may be a repeat question but I am extremely confused, can't get anything to work and need some help regarding my issue.
Here is the current code (from online - not mine):
lbx_OFL_Results.Items.Clear()
Dim i As Integer
For i = 0 To lbx_OFL_Results.Items.Count - 1
If i > lbx_OFL_Results.Items.Count - 1 Then Exit For
If Not lbx_OFL_Results.Items(i).Contains(tbx_FindText.Text) Then
lbx_OFL_Results.Items.Remove(lbx_OFL_Results.Items(i))
i -= 1
End If
Next
The list box is called "lbx_OFL_Results"
The textbox is called "tbx_FindText"
I start by clearing the list box of all items (when the form loads, it fills the list box will all lines of the text file, so I need to clear it).
Form Load Event Code:
Dim lines1() As String = IO.File.ReadAllLines("C:\ProgramData\WPSECHELPER\.data\Outlook Folder Wizard\outlookfolders.txt")
lbx_OFL_Results.Items.AddRange(lines1)
For the rest of the code it seems to be doing some form of a 'sort search' then removing any excess results.
If anyone can suggest edits to my code, or new code then that would be sublime.
Thanks.
Thanks to #Jimi for the answer.
Code:
listbox.Items.Clear()
listbox.BeginUpdate()
For i as Integer = 0 To lines1().Length - 1
If lines1(i).Contains(searchbox.Text) Then
listbox.Items.Add(lines1(i))
End If
Next
listbox.EndUpdate()
I have another question which solves how to make this search non case-sensitive. It can be found here.

move items to the another listbox which is searched by textbox

I am beginner at programming. I'm trying to build a form based app using visual basic according to a example in youtube.
In the form I cant move a item from listbox1 to listbox2 which was searched in textbox2
When I write the first item which is placed in first row of listbox1 it moves item to listbox2 but if I try with another item it cant move to listbox2.
I would be happy if someone can help me about this case.
Here are a picture of my form and the code I use :
a Lot depends on what you are putting into the listboxes. If it is simple stuff like a, b, c, d etc it will add everything to listbox 2 as you have your code under text_changed event. Try and use a button when user stopped typing to search for the entire word.
Also add your text after the sc Call to your sc sub before the return statement as well -
Sub sc()
''Current code
''If Textbox2<text - remove, already called...
Listbox2.Items.Add(Listbox1.Text)
Listbox1.Items.Remove(Listbox1.SelectedIndex)
Return
End Sub

Write individual listbox items into different text boxes and repeat until all text boxes are full

I'm programming in Visual Basic.
I have one form.
Form 1 contains:
nameTextBox
addNameButton
namesListBox
generateButton
week1TextBox
week2TextBox
week3TextBox
week4TextBox
The user needs to go to Form 1 and type a name in the text box, then add the name to the List Box. The user will add 4 names to the List Box. So, the ListBox will contain the names: Adam, Brenda and Carol.
When the generateButton is clicked, the 3 names have to be written to the text boxes in that order. So week1TextBox should contain "Adam", week2TextBox should contain "Brenda", etc... but once the last name (in this case "Carol") is written into the text box, the loop should start over. Ultimately, there may be up to 50 week text boxes (so week50TextBox). So the loop needs to repeat over and over.
As there is a lack of source code in your question, I'm really not sure exactly how the layout should look, I can only offer some advice/suggestions.
I would recommend creating your listbox control, input textbox, and button to add names to the listbox. In addition to these, though, also add a scrollable panel. (Not sure what the exact term for that control is in VB.net; it's been a long time since I've worked with that language.) Because it sounds like there might be a variable number of items on the panel, when the user goes to generate the list of names, I would use the following rough pseudocode:
Dim OutputTexts As New ArrayList ' This is only here if you want to work with these textboxes later
Private Sub CreateOutput() Handles btnGenerate.Click
pOutputPanel.Controls.Clear()
OutputTexts.Clear()
Dim NextX As Integer = 0 ' Pretty much unnecessary value, but included in case you want to mess with this
Dim NextY As Integer = 0
For i As Integer = 0 To Convert.ToInt32(txtWeekCount.Text)
Dim txtName As New TextBox
txtName.Text = lbNameList.Item(i Mod lbNameList.Items.Count)
txtName.Location = new Point(NextX, NextY) ' Play with this as necessary
NextY += 50 ' Play with this as necessary
OutputTexts.Add(txtName)
pOutputPanel.Controls.Add(txtName)
Next
End Sub
Again, this is very much pseudocode, so I would not encourage copying and pasting, but give it a read, make sure you understand all of it, and then try implementing something similar. There might be an easier way to do it, but I have not programmed in VB.NET in probably over 2 years (at least). Nonetheless, the most important thing in here is the following line: lbNameList.Item(i Mod lbNameList.Items.Count). By Mod-ing your indexing variable, you will be accessing items sequentially, and then repeating from the start of the ListBox items collection once i is out of range.
I would also encourage you to dynamically generate your TextBox controls as needed rather than manually adding in 50 or more TextBox controls.

Explanation of vba code in a word document having .docm extension

I have a Microsoft Word document with .docm format. A first glance it does not contain any macros (as when clicking the following on the ribbon; View -> Macros -> View macros pops up a window having an empty list).
But when enabling the Developer ribbon tab, and clicking the Visual Basic icon there, and then selecting the Document and ContentControlonEnter from the dropdowns in the VB window the following code appears:
Private Sub Document_ContentControlOnEnter(ByVal ContentControl As ContentControl)
Dim i As Long, j As Long
With ActiveDocument
If ContentControl.Title = "Classification" Then
ContentControl.DropdownListEntries.Clear
For i = 1 To .ContentControls.Count
If Left(.ContentControls(i).Title, 5) = "Level" Then
j = j + 1
ContentControl.DropdownListEntries.Add Text:=j & " - " & .ContentControls(i).Range.Text
End If
Next
End If
End With
End Sub
Selecting the other options in the dropdowns give only "blank" code (that is they contain only function declarations followed by theEnd keyword).
My question is what is the code meant to do?
*
Details:
The Word document in question contains hyperlinks to parts of the same document and a couple of links to Word files and Excel files of the same folder. It also contains lots of content control boxes, which I'm guessing is the focus of the code (as the code contains the ContentControl keyword)
Content controls can trigger macros when the user enters and exits them. Microsoft made the design decision that all content controls should trigger the same "events" - Document_ContentControlOnEnter / Document_ContentControlOnExit - and that the code in the event needs to check which content control was entered / exited.
Content controls are considered as part of the Document because the Document can trigger events. That's why they're in (and MUST be in) the ThisDocument class module.
(Note: View Macros can only show you PUBLIC SUB procedures with no arguments that are located in "normal" code modules. Any Private Sub, any Function, anything that takes a parameter and anything in a class module will not appear in that list. So you can't use that list to determine whether a document contains any code.)
The If ContentControl.Title = "Classification" Then checks which content control was entered. (Note: it usually makes more sense to use Select Case rather than If, especially when the event needs to distinguis between multiple content controls.) What's inside the If only executes if it was a content control with the Title "Classification". (Note that more than one content control can have the same Title, so more than one content control could run the code.)
If another content control is entered, the event is still fired, but nothing happens (in this case).
Catalin Pop correctly explained that the code is, in essence, "resetting" the drop down list.
Legacy Form fields use a similar pattern - macros can fire when the user enters/exits an form field. But the design for that was you had to create a Public Sub and assign that to the form field in the Properties.
I think the logic here is quite simple.
Basically the code searches for a content control named Classification within the entire document.
After it finds it, it clears all of its drowdown entries - like a reset.
After the cleaning part it again searches through the entire document for all content control that start with word "Level" and it collect the text for those controls and their order in appearance.
With this info collected it then fills the dropdown optios for the classification control above. (e.g. 1 Level X, 2 Level Y.. - based on what it finds in the document for controls starting with Level in their name)

VB in Access: Combo Box Values are not visible in form view but are visible through Debug.Print

Code in Form onLoad:
country_combo.RowSourceType = "Value List"
Code in a reset function:
Dim lListIndex As Long
With Me.country_combo
For lListIndex = .ListCount - 1 To 0 Step -1
.RemoveItem (lListIndex)
Next lListIndex<br/>
End With
Code to populate country combo:
*For n = 1 To numCountries*
*countryCombo.AddItem (countryRS.Fields("countryName"))*
*countryRS.MoveNext*
*Next n*
I'm having a problem that occurs AFTER the code to populate the country combobox runs. The values are there as I can run Debug.Print(countryCombo.Value) and it prints out the name of the selected country, but I can't see the values in the combobox at all. They're invisible, and as far as I know there is no visiblity property for specific items, unless I'm completely mistaken.
comboBoxError.png http://img110.imageshack.us/my.php?image=comboboxerror.png
I think you should probably use Access's GUI tools to do what you're looking for. In design mode, click on the field you are trying to populate, then click the "lookup" tab. You can then specify a table to populate the field with and your forms should automaticly update as well.
I've also seen what you describe here - as far as I can tell, it's a bug within Access (I was using 2007) that only occurs when you programatically mess with the contents of a combo box. It does not happen every time. The issue corrects itself if you highlight the text that is in the combo box.
I am experiencing a similar issue with Access 2003. Based on the selection of one combo box, the row source of a listbox is set to an SQL string Basically a SELECT DISTINCT [MyField_Selected] FROM MyTable. For some fields the values are visible in the list box and others it is not. The values are there however as I can access them via code. To make it more interesting it works fine in Access 2007.
Just found the resolution on another forum. Check the format property of the field(s) in question on the table. In my case, when Access 2007 created the table, it put an # format in there. I removed that and all works great!