How do I locate a Word application window? - windows

I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it?

You can use the Word COM object to open the work document and then you manipulate it. Make sure to add a reference for Microsoft Word first.
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop.Word
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strFileName As String
Dim wordapp As New Microsoft.Office.Interop.Word.Application
Dim doc As Microsoft.Office.Interop.Word.Document
Try
doc = wordapp.Documents.Open("c:\testdoc.doc")
doc.Activate()
Catch ex As COMException
MessageBox.Show("Error accessing Word document.")
End Try
End Sub
End Class
The doc object is a handle for the instance of Word you have created and you can use all the normal options (save, print etc). You can do likewise with the wordapp. A trick is to use the macro editor in Word to record what you want to do. You can then view this in the Macro Editor. This give you a great starting point for your VB code.
Also, be sure to dispose of the Word COM objects at the end.

I've done something similar with a SourceSafe dialog, which I posted on my blog. Basically, I used either Spy++ or Winspector to find out the window class name, and make Win32 calls to do stuff with the window. I've put the source on my blog: http://harriyott.com/2006/07/sourcesafe-cant-leave-well-alone.aspx

Are you trying to activate the word app? If you want full control, you need to automate word from your vb.net app. Check here for some samples: 1, 2

Related

How can I change the text of a label while running in visual basic?

Right now my label is having a text "hello", how can I change it to "world" by a button click while running in Visual Basic.
Write a button click event. It can be done either manually or by double clocking on the button in the designer view:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End If
Notice the end of it how it says "Button1.Click". Change Button1 to whatever the name of your button is.
Now add the code to change your textbox's text:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Textbox1.text = "world"
End If
Again note the name of the textbox and change "Textbox1" to whatever your textbox is named.
I assume you are new to learning how to program since what you asked is pretty basic. Try to find some tutorials online to help you better understand things. In this case you should look up and understand how control properties work along with events.

Visual Basic .NET (Easy way to test Form)

I have been using Java for most of my programming projects, but I got Visual Studio yesterday and want to start learning how to use Visual Basic.
I normally in Java, and can just copy and paste code into the class and rename the class name and it will work.
However, in Visual Basic this doesn't seem to be as simple as just a copy and paste and rename. All of Visual Basic .NET code is in a solution and from what I can tell there is only a main method in one form. In Java you can have a main class in each class and run the class simple like that.
I thought that you could do it the same way in Visual Basic .NET but so far have not been able to find the way to do it. I have tried making a form and then pasting in the example code into the load form and that seemed to generate no errors but didn't work neither.
Public Class GridsAndData
Private Sub GridsAndData_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Red)
Dim formGraphics As System.Drawing.Graphics
formGraphics = Me.CreateGraphics()
formGraphics.DrawLine(myPen, 200, 400, 200, 200)
myPen.Dispose()
formGraphics.Dispose()
End Sub
End Class
This was some sample code that I tried to draw a single line on a form.
You're not supposed to draw anywhere except in the Paint handler in Windows. Here's an example that works with the code you posted (placed in the correct method):
Start a new WinForms solution (File->New Project from the main menu).
Once the project is created, click on the Properties window (by default in the lower-right corner of Visual Studio). Click on the Events button (the little lightning bolt) to switch to that tab. Find the Paint item (in the Appearance section), and double-click it.
Paste your code into the generated method (which, by default, is Form1_Paint):
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint
' Paste your code here - the part below "Private Sub" and above "End Sub"
Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Red)
Dim formGraphics As System.Drawing.Graphics
formGraphics = Me.CreateGraphics()
formGraphics.DrawLine(myPen, 200, 400, 200, 200)
myPen.Dispose()
formGraphics.Dispose()
End Sub

Powerpoint VBA App_SlideShowBegin

In order to use the SlideShowBegin event in Powerpoint, you have to have a Class Module configured the following way:
Public WithEvents App As Application
Private Sub App_SlideShowBegin(ByVal Wn As SlideShowWindow)
MsgBox "SlideShowBegin"
End Sub
Then, inside of a non-class module, you have to create an object of that type and set the App to Application.
Dim X As New Class1
Sub InitializeApp()
Set X.App = Application
End Sub
Now, the only issue I have is, if you don't manually called InitializeApp with the Macro Menu in Powerpoint, the events don't work. You have to call this sub before anything can called at the beginning of a slideshow INCLUDING this sub.
How can I go about calling this sub before running my powerpoint? Is there a better way to do this?
EDIT:
I've tried using Class_Initialize but it only gets called once it is first used or you make a statement like Dim X as Class1; X = new Class1
Usually event handlers are installed as part of an add-in, where you'd initialize the class in the Auto_Open subroutine, which always runs when the add-in loads. If you want to include an event handler in a single presentation, one way to cause it to init is to include a shape that, when moused over or clicked fires a macro, which inits your event handler and goes to the next slide.
Answering to an old question, but I hope my solution might helpt somebody ending up at this question.
The general advice for this issue is using a plug-in or placing some element on the slide and when that is clicked or hovered perform the initialization. Both are not always desired so I have the following approach:
In some module:
Dim slideShowRunning As Boolean
-----------------------------
Sub SlideShowBegin(ByVal Wn As SlideShowWindow)
' Your code for start-up
End Sub
-----------------------------
Public Sub OnSlideShowPageChange(ByVal Wn As SlideShowWindow)
If TypeName(slideShowRunning) = "Empty" Or slideShowRunning = False Then
slideShowRunning = True
SlideShowBegin Wn
End If
End Sub
----------------------------
Public Sub OnSlideShowTerminate(ByVal Wn As SlideShowWindow)
slideShowRunning = False
End Sub
For me this works perfectly. NOTE I am by no means a vba expert, actually I might have less than 50 hours of vba programming (maybe only 8 in powerpoint). So this might be an horrible solution. I don't know, but for me it works so I liked to share.
In fact, OnSlideShowPageChange runs when slideshow begins. Just make sure it doesn't work in the subsequent page changes if not needed using a global variable. See answer from C. Binair for details.

How to save an Excel file via VB 2010 without any dialogs (such as "save as")

I am trying to Save an Excel file Via VB 2010, and I have these questions
How can I disable the "save as" dialog? I tried things such as only "save" instead of "save as", but it doesen't work...
After I saved the file (using the save as) I can't Delete it... (I tried closing the excel file, Visual basic etc...) all i get is an error saying it is allready open in excel...
Is there a way to make VB show me the tips for writing the excel stuff (Ie - when I write messagebox. - it pops up "Show" for help. how can I enable this for excel code [worksheets.cells. ect.])
the connection:
Sub Connect()
' Connect to the excel file
oExcel = CreateObject("Excel.Application")
'Devine the workbook
oBook = oExcel.workbooks.open("e:\Words\Heb.xls")
End Sub
the saveas:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
oExcel.SaveAs(oExcel.Path & ".xls")
End Sub
Thanks a lot
I think Inafiziger has solved your main issue, it should be a vanilla Save.
As it was unclear to me exactly what your are doind (ie Visual Studio/VB/BA) then
On (1)
I thought it worth clarifying that you can use code inside the ThisWorkbook module to detect and handle a SaveAs if you are providing users with a choice. This Event detects the SaveAs and cancels it
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If SaveAsUI Then
MsgBox "You cannot use SaveAs to save this file", , "Save Cancelled!"
Cancel = True
End If
End Sub
This code can be programmatically added to your target workbook but I doubt you would need to resort to this given you should be able to run the simple Save.
On (3)
You need to use Early Binding to get the benefit of intellisense. You are currently use late binding with oExcel = CreateObject("Excel.Application"). A commonly used approach is to write the code and get it working with early binding, then converting it to late binding for final code publication.
Conditional Compilation (see comment at bottom) can be used to switch between the two binding methods within the same code.
You should be saving the workbook. e.g. oBook.Save.
If you create a new file, you will need to use SaveAs with a valid filename in order to save it the first time.

How to copy to clipboard using Access/VBA?

Using VBA inside Access2003/2007.
How to copy the contents of a string variable to the clipboard?
This site recommends a creating a zero length TextBox, copying the string to the TextBox, then running DoCmd.RunCommand acCmdCopy. Ugh. I mean, we may go down the route. But still. Ugh.
While the MS knowledgebase article shows us how to do it but it involves a number of Windows API calls. Yuk.
Are those the only two options?
VB 6 provides a Clipboard object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA.
If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason.
However, a simpler alternative is to use the DataObject class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly.
For example, to place some text on the clipboard, you could use the following code:
Dim clipboard As MSForms.DataObject
Set clipboard = New MSForms.DataObject
clipboard.SetText "A string value"
clipboard.PutInClipboard
Or, to copy text from the clipboard into a string variable:
Dim clipboard As MSForms.DataObject
Dim strContents As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
strContents = clipboard.GetText
User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:
http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878
You can get Leigh Webber's source code here
If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.
I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access.
Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).
With his classes, this is what it takes to copy to/from the clipboard:
Dim myClipboard As New vbaClipboard ' Create clipboard
' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"
' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)
He also provides other functions for manipulating the clipboard.
It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.
-Jim
I couldn't figure out how to use the API using the first Google results. Fortunately a thread somewhere pointed me to this link:
http://access.mvps.org/access/api/api0049.htm
Which works nicely. :)
Easy TWO line code:
It's not so complicated, I don't understand why all solutions found in the net are so complicated.
Sub StoreData()
Set objCP = CreateObject("HtmlFile")
objCP.ParentWindow.ClipboardData.SetData "text", "Some text for clipboard"
End Sub
There are many examples listed here but none seem to cover the direct way of using the API that also works with Access and Excel 32 bit and 64 bit.
I don't want to steal anyone else's work so I'm pointing to an article that has a solution.
https://stackoverflow.com/a/35512118/1898524
Following up on David's idea, if you want to pass in an argument, it has to be double-quoted.
Public Sub SetClipboardText(ByVal Text As String)
Dim QuotedText As String
QuotedText = """" & Text & """"
Set HtmlFileObject = CreateObject("HtmlFile")
HtmlFileObject.ParentWindow.ClipboardData.SetData "text", Eval(QuotedText)
End Sub

Resources