Event change of table in Word - vba

Private Sub Document_Change(ByVal Target As Range)
Set table = ActiveDocument.Tables(1)
If Not Intersect(table, Target) Is Nothing Then
Target.AutoFormat ApplyColor: Red
End If
End Sub
I have the following code, but it does not seem to work in VBA Word.
Can anyone help me out?

I suppose that you copied the code from Excel VBA and tried to rebuild it a bit.
There are a few differences between Excel and Word VBA.
Intersect does not exist in Word VBA.
DocumentChange event in Word works differently from what you would expect - It occurs when a new document is created, when an existing document is opened, or when another document is made the active document. (https://msdn.microsoft.com/en-us/library/office/ff822189.aspx)
If you want to make changes in red, you may do the following:
Record the wholeDocument in a static string.
When there is a change - record again in a new string.
Compare the strings and color the differences.
However, this is a bit tough, as far as word does not have Changeevent as we are expecting it (e.g. as in Excel). Thus, you should run the VBA code a few times automatically.

Related

Use a Userform for MS Word to Input to Values in Form Fields

I am trying to automate a repetitive manual task for another department. They have a word template several pages long. They have to enter data several times each time they use it. Many of these are repetitive "fields". I thought about setting up custom form fields. But having them go through the navigation and know the field names to update them is not optimal. I found one solution to create a bookmark for each data input, and create links to that bookmark where it needs to be repeated - better but not optimal. I was hoping to create a userform where they can enter all the data and have it populate bookmarks, custom fields, to whatever.
I found a video that does this, but when I try the code, it does not update the bookmark. i created userform with Textbox1, and a CommandButton, and a bookmark in the document called MWDate. The code I am trying to get to work is:
Private Sub CommandButton1_Click()
Dim MWDate As Range
Set MWDate = ActiveDocument.Bookmarks("MWDate").Range
MWDate.Text = Me.TextBox1.Value
Me.Repaint
UserForm1.Hide
End Sub
This is a code example I grabbed and modified from the tutorial video. I don't know what the "Me." is. It does not populate the bookmark, which tells me it is not getting to the repaint line. Nor does it ever get to the hide line.
Anyone have a fix? Or a better way? Thanks for any help you can give.

Excel Data type/validation - pulling in the correct data

I have a macro. Code part is fairly simple:
Sub Test()
Worksheet.Range("A1").Value = ws.Range("A2").Value2
End sub
Working just fine for ~6,000 lines. One line is causing problems, formatted like so:
12345A0
Now, there are quite a few other lines like this. They process just fine. This cell, Excel thinks it's a Number, and flags a warning that "Hey this is a number". It then only pulls in
12345
and truncates the rest of the cell, seeming to figure "Oh, it's a number, I'm fixing it." But I need the entire ID. What is a simple way to get Excel to think "Hang on, I need to get the actual cell contents" - Is there an easy way to do this? (Programatically - this part is part of code that cycles through different sheets and workbooks given to us, and a manual fix will not work)
Edit: Copying and pasting the cell produces 12345 - the ending is truncated.
Edit 2: Selecting the data inside of the cell and hitting enter changes the cell to 12345. What's going on Excel? Excel 2010 since this might be relevant
Edit 3: Application.ErrorCheckingOptions.NumberAsText = False doesn't do anything besides remove the flag - Excel is still convinced that it's a number in the cell, and not a string. Nevermind what data type we give it.

Word 2010 VBA: add text to template without deleting everything below

I have been writing a code to build a custom document for weekly reporting. I had it set to create a new doc, build the tables, format everything, insert a logo, etc., and I hit a wall when Word crashed every time I tried to resize the logo through VBA. It then occurred to me that I was doing this the wrong way anyway, and that I should build a template, have the code open that template, and then insert the changes directly into that document.
When I add text to the range I need, everything below is deleted. I have three lines of a header; the third line is variable and will change each week. Below that I have three tables, some cells of which will be updated each week. Right now I am just stuck at the third line of the document.
Here is an example of what I have. It is extremely short because I started anew and hit a dead end immediately.
Dim Template as Document
Set Template = ThisDocument
Dim InsertSpot as Range
Set InsertSpot = Template.Range(46)
InsertSpot.Text = "Hello"
When I run that, everything is deleted below "Hello".
I tried some different things, such as:
Set InsertSpot = Template.Range(46,50)
InsertSpot.InsertAfter "Hello"
That doesn't work; it just adds "Hello" to the first cell of the first table.
I feel silly being stuck at such an elementary part, but I honestly have no idea what to do here. Everything I looked at online talked about how to insert text at a bookmark without deleting the bookmark. I just want to enter text, period.
Any thoughts?
I found the answer. I did the following:
Dim Template as Document
Set Template = ThisDocument
Dim InsertSpot as Range
Set InsertSpot = Template.Range(46, 46)
InsertSpot.Text = "Hello"
I had to list both the starting AND the ending character so that the inserted text would not bleed over into the rest of the page. Hope I helped someone else who is having a similar problem. Unfortunately Word VBA is pretty lacking in support and clear explanations.
other alternatives can be
ThisDocument.Range(46).InsertBefore "Hello"
ThisDocument.Tables(1).Range.InsertBefore "Hello"
ThisDocument.Paragraphs(3).Range.InsertAfter "Hello"

Extract data from content controls in Word to Excel

I have a Word document that is "form-fillable", i.e. it has content control objects in it such as rich text and date picker content controls. I am looking to extract the data from specific fields into Excel. For example, every form has the project title, start date, and manager. I would like 1 row for that form with those three pieces of data. Eventually this will need to be done for a few hundred of these forms every few months, but for now I'd like to just start with one.
I envision having a button on the Excel sheet that will run VBA code to pull the data from the Word document, and populate the proper cells in the sheet. With the filepath for the Word doc being specified by the user.
I am new to VBA. How do I point my code at the right file, and then again at the specific field I need? Do I give the fields titles in the Word doc?
This is in MS Office '13
Your application is going to have a large number of specific details which are difficult to address without the specifics. To get started, here is some very simple code to get the Date from a drop-down in Excel from Word.
Note to work with Word, you need to create a reference to "Microsoft Word 15.0 Object Library" on the Excel side. Tools -> References in the VBA Editor.
When working across applications, it can help to write the VBA in Word and then move it over to Excel once you have the properties you want.
This VBA for the Excel side of the equation:
Sub GetDataFromWordFile()
Dim wrd As Word.Application
Dim file As Word.Document
Set wrd = New Word.Application
Set file = wrd.Documents.Open("test.docx")
Range("A1") = file.ContentControls(1).Range.Text
file.Close
wrd.Quit
End Sub
My Word file includes a single ContentControl. Not sure how you address the ones you want (trial and error?).
The Excel side drops the date in the right place.

Sheet.Activate changes sheet but continues to edit data on previous sheet

I have a dialog box with a couple of buttons that launch macros to activate and change to different sheets.
The problem I am having is after I click the button, the macro activates the new sheet and I see it. But when I go to delete data, add data or try to delete a row "Nothing happens" the data on the screen is still there. If I go back to the previous sheet, the cells and rows that I had intended to delete were deleted in that sheet. It is very wierd and never seen anything like that. It appears that my macro code is note doing enough to actually change to the new sheet. I do not have this problem if I click a different sheet tab to change to it. Or if I click the dialog button to go to the new sheet and quickly do a ctrl-pgDown and Ctrl-PgUp to change from another tab and back that seems to fix the problem.
This is the code in my macro I am using to try to change to the desired tab.
Private Sub Report1Button_Click()
On Error GoTo Handler
Sheets("Report1").Activate
If StayOpenBox.Value = False Then
Unload MainMenu
End If
Exit Sub
Handler:
MsgBox "Sheet 'Report1' not found or renamed"
End Sub
Thanks for any help or suggestions
UPDATE:
Here is code that I use to call the dialog box. I have a shape on the other sheet that is assigned to this macro to open dialog box
Sub ShowMainMenu()
With UserForm1
.Show
End With
End Sub
Also there is no further code to make edits to the new sheet. My Button click simply switches to the other sheet and when I attempt to make edits manually, they are actually done on the previous sheet which is not the one I am currently looking at. So anything I do, Bold text, delete text, delete row, etc, is not done on the current sheet I am looking at, but when I return to the previous sheet the changes where made there. Im on Excel 2013, I have reproduced this problem in 2 separate files, but I will try on a different computer and older version of excel. Screenshot of my situation is below.
UPDATE 2:
I ran this xlsm file on a 2nd computer with Xls 2007 and was not having the problem. So I ran the macro on a 3rd computer that also has Excel 2013 and it is experiencing the same problem. So it is not computer specific and seems to be a problem in XLS 2013 but not in XLS 2007. I will try to find a computer with Excel 2010 to test as well, but something about this code is causing a problem in 2013 but not in older versions of excel.
When you run VBA code, it will default to using the ActiveSheet if you don't define the Sheet. When you have objects/methods that you want performed on a specific sheet, you should always specify! You can do that one of two ways:
Sheets("Report1").[Object].[Method]
'or
Sheets("Report1").[Method]
or you can pass the Sheet name to a variable and use that for shorter code
Dim Report1 As Worksheet
Set Report1 = Sheets("Report1")
Report1.[Object].[Method]
'or
Report1.[Method]
Try changing the sequence of lines in your code. I had a similar situation and it turned out that I inserted the "delete sheet" code in between the commands that were copying data from sheet1 to sheet2. When I put the deletion lines (commands) after I finished copying sheets everything started to work correctly. Many commands activate one sheet while performing and this immediately disactivates another sheet. So if you used "ActiveSheet" sommand somewhere it may be incorrectly understood - the command may be executed not on the sheet you meant.
Just use the full address for the range you are trying to manipulate, for example instead of:
Sheets("mySheet").Activate
Range("A1:B10").Cut
Sheets("myOtherSheet").Activate
Range("A1:B10").Paste
use:
Sheets("mySheet").Range("A1:A10").Cut Destination:=Sheets("myOtherSheet").Range("A1:B10")
I just had the same problem, also with Excel 2013. So even if the thread is over 9 month inactive, I want to share my solution in case somebody gets here through a Google search.
The solution was really simple. Call the userform with:
UserForm1.show vbModeless