Vba open excel from word

I want to open a Excel sheet through Word VBA, paste information from the Word document row wise and save it. I have code for picking up specific information from the Word document but do not know how to open Excel and save it.

I have found a solution in the following site:
http://www.exceltip.com/st/Control_Excel_from_Word_using_VBA_in_Microsoft_Excel/463.html

It is giving an error and also I do not know how to add a reference to the Excel library in Word.

Error: Dim xlApp As Excel.Application — Compile Error «User defined type not defined»

niton's user avatar

niton

8,57921 gold badges32 silver badges52 bronze badges

asked Nov 3, 2011 at 13:47

JavaBits's user avatar

You could do one of two things here —

1) Change «Excel.Application» and «Excel.Workbook» to «Object»
(late bound)

or

2) In the VBA Editor, go to Tools > References and look for «Microsoft Excel x.0 Object Library» and check the checkbox.
(early bound)

The ‘x’ depends on your Excel version. 11.0 is Office 2003, 12.0 is Office 2007, and so on.

answered Nov 3, 2011 at 13:52

JimmyPena's user avatar

JimmyPenaJimmyPena

8,6986 gold badges43 silver badges64 bronze badges

  • #1

I need to open an excel file from word («C:Documents and SettingsHartGMy DocumentsDave SlaterImport.xls»)
and then run a macro from the excel file called «DelTabs».

I have the code below that I tohught would open the excel file but it’s not working…Any help on this would be most apreciated.

Dim oExcel As Excel.Application
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open(«C:Documents and SettingsHartGMy DocumentsDave SlaterImport.xls»)
‘Rest of code
End Sub

Many thanks in advance

Repeat Last Command

Pressing F4 adds dollar signs when editing a formula. When not editing, F4 repeats last command.

  • #2

Code:

[COLOR="Blue"]Sub[/COLOR] OpenExcelFile()
    
    [COLOR="Blue"]Dim[/COLOR] oExcel [COLOR="Blue"]As[/COLOR] Excel.Application
    [COLOR="Blue"]Dim[/COLOR] oWB [COLOR="Blue"]As[/COLOR] Workbook
    [COLOR="Blue"]Set[/COLOR] oExcel = [COLOR="Blue"]New[/COLOR] Excel.Application
    [COLOR="Blue"]Set[/COLOR] oWB = oExcel.Workbooks.Open("C:Documents and SettingsHartGMy DocumentsDave SlaterImport.xls")
    [COLOR="Red"][B]oExcel.Visible = [COLOR="Blue"]True[/COLOR][/B][/COLOR]
    [COLOR="Blue"]Set[/COLOR] oWB = oExcel.Workbooks.Open(sPath)
    'Rest of code
    
[COLOR="Blue"]End[/COLOR] [COLOR="Blue"]Sub[/COLOR]

  • #3

Many thanks. Worked a treat. i just had to remove Set oWB = oExcel.Workbooks.Open(sPath).

sorry to be a pain but do you know how I can — once the excel is open then run a macro from within the excel file?

  • #4

Adjust paths. Module1 is the module containing macro. ShowMsg is a macro which is actually laucnhed.

Code:

[COLOR="Blue"]Sub[/COLOR] OpenExcelFile()
    
    [COLOR="Blue"]Dim[/COLOR] oExcel [COLOR="Blue"]As[/COLOR] Excel.Application
    [COLOR="Blue"]Dim[/COLOR] oWB [COLOR="Blue"]As[/COLOR] Excel.Workbook
    [COLOR="Blue"]Set[/COLOR] oExcel = [COLOR="Blue"]New[/COLOR] Excel.Application
    [COLOR="Blue"]Set[/COLOR] oWB = oExcel.Workbooks.Open("k:Test.xlsm")
    oExcel.Visible = [COLOR="Blue"]True[/COLOR]
    oWB.Application.Run "Module1.ShowMsg"

[COLOR="Blue"]End[/COLOR] [COLOR="Blue"]Sub[/COLOR]

  • #5

Got it, thanks very much…Most appreciated.

  • #6

Not at all! Glad that helped ya! :)

  • #7

Code:

[COLOR=Blue]Sub[/COLOR] OpenExcelFile()
    
    [COLOR=Blue]Dim[/COLOR] oExcel [COLOR=Blue]As[/COLOR] Excel.Application
    [COLOR=Blue]Dim[/COLOR] oWB [COLOR=Blue]As[/COLOR] Workbook
    [COLOR=Blue]Set[/COLOR] oExcel = [COLOR=Blue]New[/COLOR] Excel.Application
    [COLOR=Blue]Set[/COLOR] oWB = oExcel.Workbooks.Open("C:Documents and SettingsHartGMy DocumentsDave SlaterImport.xls")
    [COLOR=Red][B]oExcel.Visible = [COLOR=Blue]True[/COLOR][/B][/COLOR]
    [COLOR=Blue]Set[/COLOR] oWB = oExcel.Workbooks.Open(sPath)
    'Rest of code
    
[COLOR=Blue]End[/COLOR] [COLOR=Blue]Sub[/COLOR]

Hi

When I run this code, I get error message «Type defined by user not defined» (translated from Portuguese, maybe not exactly this in English).

Please, how do I fix it?

  • #8

Hi

When I run this code, I get error message «Type defined by user not defined» (translated from Portuguese, maybe not exactly this in English).

Please, how do I fix it?

In the Visual Basic window, go to the menu bar: Tools > References.
Make sure the box for «Microsoft Excel 15.0 Object Library» (or something similar) is checked.

  • #9

Hello,

I’m using the following code to open an Excel files (located in our company server) from a Word document. It does work well but I have a little concern. Usually, when I manually open this excel file, if someone in the company has it already open, I’ll receive a notification that the file is in edit mode with Mr.Someone and give me the choice to
1- «Read-Only» (Open it in Read-Only)
2- «Notify «Open it and get notify when the other user exit the excel so I became in edit mode»
3 — Cancel

When using the below code, if someone has the file already open, it will open directly in Read-Only and I will never get that little pop-up that give me the 3 choices. Can I modify the code to get that pop-up before the file is open ?

Code :
Sub OpenIndex()

Dim Index As String
Dim oExcel As Excel.Application
Dim oWB As Excel.Workbook

Index = «G:xxxxxxxxIndex.xlsx»

Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open(Index)
oExcel.Visible = True

End Sub

  • #10

Any idea ?

See the «pop-up» below I’m talking about. When using my Macro, if the file is already in use, it will open it automatically in Read Only in lieu of showing that window. Can I modify my code to have this window appears when the file is already in use by someone else ?

excel-file-in-use.png

Code:

[COLOR=#333333]Sub OpenIndex()[/COLOR]

[COLOR=#333333]Dim Index As String[/COLOR]
[COLOR=#333333]Dim oExcel As Excel.Application[/COLOR]
[COLOR=#333333]Dim oWB As Excel.Workbook[/COLOR]

[COLOR=#333333]Index = "G:xxxxxxxxIndex.xlsx"[/COLOR]

[COLOR=#333333]Set oExcel = New Excel.Application[/COLOR]
[COLOR=#333333]Set oWB = oExcel.Workbooks.Open(Index)[/COLOR]
[COLOR=#333333]oExcel.Visible = True[/COLOR]


[COLOR=#333333]End Sub[/COLOR]

Содержание

  1. Как открыть Excel из Word макросом VBA? Запуск Excel из Word
  2. Макрос, запускающий Excel и открывающий новую рабочую книгу
  3. Макрос, запускающий Excel и открывающий заданный файл
  4. Control Excel from Word using VBA in Microsoft Excel 2010
  5. VBA-open excel file from word
  6. george hart
  7. Excel Facts
  8. Sektor
  9. george hart
  10. Sektor
  11. george hart
  12. Sektor
  13. Ryan of Tinellb
  14. PL dub
  15. Copy data from Single or Multiple Tables from Word to Excel using VBA
  16. Tools you can use
  17. Modify embedded Excel workbook in Word document via VBA
  18. 4 Answers 4

Как открыть Excel из Word макросом VBA? Запуск Excel из Word

Если в макросе, написанном для Microsoft Word, требуется обратиться к данным, хранящимся в файле какого-либо другого приложения, например Excel, или наоборот, передать данные из Word в такой файл, то возникает необходимость запуска того приложения, в формате которого сохранен файл. Ниже приведены программные коды макросов VBA для Microsoft Word, запускающие приложение Excel.

Макрос, запускающий Excel и открывающий новую рабочую книгу

Если для передачи данных из Outlook в Excel нужна новая рабочая книга, можно воспользоваться примером кода, приведенного ниже.

Для того, чтобы перенести этот программный код на свой компьютер, наведите курсор мыши на поле с программным кодом, нажмите на одну из двух кнопкок в правом верхнем углу этого поля, скопируйте программный код и вставьте его в модуль проекта на своем компьютере (подробнее о том, как сохранить программный код макроса).

Макрос, запускающий Excel и открывающий заданный файл

Если же для передачи данных из Outlook в Excel, или наоборот, требуется открытие какого-либо определенного файла, то можно использовать следующий код:

При копировании этого кода на свой компьютер, не забудьте изменить путь к файлу. Запуск приложения можно сделать и невидимым, если в коде изменить True на False.

Источник

Control Excel from Word using VBA in Microsoft Excel 2010

There are times we have to copy data from a word document to an excel file. We can do this very easily with a macro in all version of office. The macro will open an existing / new excel file, copy the contents and then save and close the file. Lets see how this is done.

Sub OpenAndReadWordDoc()
Dim tString As String
Dim p As Long, r As Long
Dim wrdApp As Object, wrdDoc As Object
Dim wb As Workbook
Dim trange As Variant

Set wb = Workbooks.Add
With wb.Worksheets(1).Range(“A1”)
.Value = “Word Document Contents:”
.Font.Bold = True
.Font.Size = 14
.Offset(1,0).Select
End With

Set wrdApp = CreateObject(“Word.Application”)
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open(“B:TestMyNewWordDoc.docx”)

With wrdDoc
For p = 1 to .Paragraphs.Count
Set trange = .Range(Start:=.Paragraphs(p).Range.Start, _
End:=.Paragraphs(p).Range.End)
tString = trange.Text
tString = Left(tString, Len(tString)-1)

If Instr(1, tString,”1”) > 0 Then
wb.Worksheets(1).Range(“A” & r).Value = tString
r=r+1
End If

wrdApp.Quit
Set wrdDoc = Nothing
Set wrdApp = Nothing
wb.Saved = True

To copy the above code to your file,

  • Press Alt + F11 on the keyboard
  • On the left hand side, you will see Microsoft Excel Objects
  • Right click and select Insert
  • Then click on Module
  • Copy the code to the code window on the right

Now lets see how this code works –

First we declare the variables we need –tstring as a string to hold text (we will see what text later). 2 variables “p” & “r” as counters. These are of the “long” type. Then we have the 2 object variables wrdApp and wrdDoc. wrdApp is the word application object and wrdDoc is the Word document object. Wb is our workbook variable for the new workbook which is created in the code. If you are opening an existing workbook, you can assign this variable to that instead. The last variable is the trange variant type of variable which will have the contents that need to be transferred from the word doc to the excel file.

Set wb = Workbooks.Add

This assigns the new workbook to the wb variable. If you do not want to add a new workbook but open an existing workbook, then you can alter this line as follows –
Set wb – Workbooks.Open(“B:TestFile1.xlsx”)

With wb.Worksheets(1).Range(“A1”)
.Value = “Word Document Contents:”
.Font.Bold = True
.Font.Size = 14
.Offset(1,0).Select
End With

The With wb.Worksheets(1).range(“A1”) is a quick way of referencing it. So you do not have to repeat it for each of the code lines between the With and End with statements.

These lines of code put in the text “Word Document Contents:” with a bold font and font size 14 in cell A1 of the 1 st worksheet in the new workbook. And then .Offset(1,0).Select selects the next row.

The variable “r” is assigned a value 3 as this is the starting row in the excel file for the data to be copied from the word document.

Set wrdApp = CreateObject(“Word.Application”)

If Word is already running in your system,CreateObject will create a new instance of Word. So this line assigns the object variable wrdApp to the Word Application which you can use later in the code.

The newly created instance of Word will not be visible when its being created. To make it visible, you need to set wrdApp.Visible = True so that its visible.

Set wrdDoc = wrdApp.Documents.Open(«B:TestMyNewWordDoc.docx»)

We created the new instance of the word application but we haven’t opened a source word document yet. So this command will open the word document. The object wrdDoc has been assigned to this document so we can use it later in the code.

With wrdDoc….End With

This is our “With” loop which will work entirely with the wrdDoc object. Once you open this loop, you do not have to repeat the text “wrdDoc” again in this loop. You can directly start with the dot (“.”) before any objects relating to wrdDoc. This loop ends with the End With statement. Once the End With statement has been input, you cannot refer to the objects after wrdDoc with just the “.”.

For p = 1 to .Paragraphs.Count

This is the “For” loop which will loop from the 1 st to last paragraphs in the word document. The word file which contains the data has 100 lines of information, each stored as a separate paragraph. The loop will increment from 1 to 100 and copy the paragraphs. If certain conditions are set, the copy paste will be based on those conditions.

Set trange = .Range(Start:=.Paragraphs(p).Range.Start, End:=.Paragraphs(p).Range.End)

This assigns the start and end of each paragraph to range as the loop increments.

tString = trange.text
tString = Left(tString,len(tString)-1)

First the text from trange is passed on to TString. Then each paragraph has a paragraph character at the end of the sentence. This is removed using the Left function. From the left side, all characters except the last one is stored in the tString variable.

If Instr(1, tString, “1”) > 0 Then
wb.Worksheets(1).Range(“A” & r).Value = tString
r=r+1
End If

This IF function checks if the text in tString contains the number 1. If it is true, then it copies the contents of tString to the next available row in the workbook. “r” first had a value of 3. Using r=r+1, we increment it by 1, so that the next entry can be placed below the previous entry.

The Next p line of code increments to the next paragraph.

.Close closes the document once all the paragraphs have been worked on. This is the output we get in the excel file –

You will see that only those paragraphs which contain number 1 anywhere in the number are included in the output.

wrdApp.Quit
Set wrdDoc = Nothing
Set wrdApp = Nothing
wb.Saved = True

wrdApp.Quit will close the word Application. Set wrdDoc = Nothing and Set wrdApp = Nothing will release the memory taken by these 2 object variables and set them to Nothing. wb.Saved = True will save the workbook.

With above code we can control which data to be copied from word file to excel file.

Источник

VBA-open excel file from word

george hart

Board Regular

I need to open an excel file from word («C:Documents and SettingsHartGMy DocumentsDave SlaterImport.xls»)
and then run a macro from the excel file called «DelTabs».

I have the code below that I tohught would open the excel file but it’s not working. Any help on this would be most apreciated.

Dim oExcel As Excel.Application
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open(«C:Documents and SettingsHartGMy DocumentsDave SlaterImport.xls»)
‘Rest of code
End Sub

Many thanks in advance

Excel Facts

Sektor

Well-known Member

george hart

Board Regular

Many thanks. Worked a treat. i just had to remove Set oWB = oExcel.Workbooks.Open(sPath).

sorry to be a pain but do you know how I can — once the excel is open then run a macro from within the excel file?

Sektor

Well-known Member

george hart

Board Regular

Sektor

Well-known Member
New Member

When I run this code, I get error message «Type defined by user not defined» (translated from Portuguese, maybe not exactly this in English).

Please, how do I fix it?

Ryan of Tinellb

New Member

When I run this code, I get error message «Type defined by user not defined» (translated from Portuguese, maybe not exactly this in English).

Please, how do I fix it?

PL dub

New Member

I’m using the following code to open an Excel files (located in our company server) from a Word document. It does work well but I have a little concern. Usually, when I manually open this excel file, if someone in the company has it already open, I’ll receive a notification that the file is in edit mode with Mr.Someone and give me the choice to
1- «Read-Only» (Open it in Read-Only)
2- «Notify «Open it and get notify when the other user exit the excel so I became in edit mode»
3 — Cancel

When using the below code, if someone has the file already open, it will open directly in Read-Only and I will never get that little pop-up that give me the 3 choices. Can I modify the code to get that pop-up before the file is open ?

Источник

Copy data from Single or Multiple Tables from Word to Excel using VBA

Tools you can use

Copying and pasting the tables from word to excel, is easy. However, if you are using VBA to automate your Excel job, then I am sure this example would come handy.

Microsoft provides the Table object (for word) in VBA, which has a collection of methods and properties with which you to read and extract data from multiple tables in a word doc, from Excel.

Let’s see the example now.

First, create a word document (.doc or .docx) and draw a table. Add few data to it. Make the first row as header. You can draw multiple tables in your word file. Save the file.

Now, open your Excel file and add a button, an ActiveX button control, in your worksheet (Sheet1).

Press Alt+F11 to open the VBA editor. You can also right click sheet1 and choose View Code option. Add Office Object Library Reference to your application.

👉 Do you know you can copy contents (paragraphs) as it is (each word in a single cell with the same font name, size, color of the text, underline etc.) from a Word file to your Excel worksheet? Yes you can. Read this article.

Write the below code inside the CommandButton1_Click() event.

See how I am using the FileDialog object in the beginning of the procedure to select the word file. After getting access to the word file, I am creating the word and doc objects to open and read the contents in the file. The doc will remain invisible.

objWord.Visible = False ‘ Do not show the file.

The tables() method from the Table object , will allow us read the doc’s table data. The method takes a parameter as index , a number, which will return a single table object.

You can define the index values like “1”, “2”, “3” etc. depending upon the number of tables you want to read and extract data from. However, If you have multiple tables in your word file, and don’t want to add indexes manually, you can use objDoc.tables.Count to get the total tables in the file and loop through each table.

After writing the data to the Excel worksheet, I am just drawing borders around the columns and rows.

Источник

Modify embedded Excel workbook in Word document via VBA

I have a Word document with two embedded Excel files (added using Insert -> Object -> Create From File) which I wish to modify using Word VBA. I have got to the point where I am able to open the embedded files for editing (see code below), but am unable to get a handle on the Excel workbook using which I can make the modifications and save the embedded file. Does anyone have a solution for this? Thanks in advance.

4 Answers 4

Yikes, don’t do what you’re suggesting in your comment. You’ll probably end up with multiple instances of Excel (check Task Manager and see how many there are after executing your code).

Firstly, add a reference to the Excel object library (Project->References & choose Microsoft Excel Object Library). Now you can declare your objects as bona-fide Excel types and use early binding rather than declaring them as «Object» and using late binding. This isn’t strictly necessary, but apart from anything else it means you get Intellisense when editing your code.

You’re doing the right thing right up until you do .OleFormat.Edit. (I would personally use .OleFormat.Activate but since I’ve never tried using .Edit I couldn’t say that it makes a difference).

Having done .Activate (or, presumably, .Edit), you can then access the OleFormat.Object member. Since the embedded Object is an Excel chart, the «Object» will be the Excel Workbook, so you can do this:

Note that you do NOT need to close Excel, and indeed you cannot — Word «owns» the instance used for an edit-in-place, and will decide when to close it. This is actually something of a problem, since there’s no obvious way to force the embedded object to be de-activated, so the chart would stay open after you execute the code above.

There is a hack-y way to get the chart to close, though. If you add tell Word to activate it as something else, it’ll de-activate it first. So, if you tell it to activate it as something non-sensical, you’ll achieve the right result because it’ll de-activate it and then fail to re-activate it. So, add the following line:

Note that this will raise an error, so you’ll need to temporarily disable error handling using On Error Resume Next. For that reason, I normally create a Deactivate method, to avoid disrupting the error handling in my main method. As in:

Источник

Если в макросе, написанном для Microsoft Word, требуется обратиться к данным, хранящимся в файле какого-либо другого приложения, например Excel, или наоборот, передать данные из Word в такой файл, то возникает необходимость запуска того приложения, в формате которого сохранен файл. Ниже приведены программные коды макросов VBA для Microsoft Word, запускающие приложение Excel.

Макрос, запускающий Excel и открывающий новую рабочую книгу

Если для передачи данных из Outlook в Excel нужна новая рабочая книга, можно воспользоваться примером кода, приведенного ниже.

Sub Zapusk_Excel_iz_Word1()
Dim objXls As Object
    Set objXls = CreateObject("Excel.Application")
    objXls.Workbooks.Add
    objXls.Application.Visible = True
    Set objXls = Nothing
End Sub

Для того, чтобы перенести этот программный код на свой компьютер, наведите курсор мыши на поле с программным кодом, нажмите на одну из двух кнопкок knopka_view_source в правом верхнем углу этого поля, скопируйте программный код и вставьте его в модуль проекта на своем компьютере (подробнее о том, как сохранить программный код макроса).

Макрос, запускающий Excel и открывающий заданный файл

Если же для передачи данных из Outlook в Excel, или наоборот, требуется открытие какого-либо определенного файла, то можно использовать следующий код: 

Sub Zapusk_Excel_iz_Word2()
    Dim objXls As Object
    Set objXls = CreateObject("Excel.Application")
    objXls.Workbooks.Open "C:Test.xlsx" 'укажите путь и имя существующего файла
    objXls.Application.Visible = True
    Set objXls = Nothing
End Sub

При копировании этого кода на свой компьютер, не забудьте изменить путь к файлу. Запуск приложения можно сделать и невидимым, если в коде изменить True на False.

Другие материалы по теме:

There are times we have to copy data from a word document to an excel file.  We can do this very easily with a macro in all version of office.  The macro will open an existing / new excel file, copy the contents and then save and close the file.  Lets see how this is done.

Option Explicit

 
Sub OpenAndReadWordDoc()
Dim tString As String
Dim p As Long, r As Long
Dim wrdApp As Object, wrdDoc As Object
Dim wb As Workbook
Dim trange As Variant

Set wb = Workbooks.Add
With wb.Worksheets(1).Range(“A1”)
.Value = “Word Document Contents:”
.Font.Bold = True
.Font.Size = 14
.Offset(1,0).Select
End With

r = 3

Set wrdApp = CreateObject(“Word.Application”)
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open(“B:TestMyNewWordDoc.docx”)

With wrdDoc
For p = 1 to .Paragraphs.Count
Set trange = .Range(Start:=.Paragraphs(p).Range.Start, _
End:=.Paragraphs(p).Range.End)
tString = trange.Text
tString = Left(tString, Len(tString)-1)

If Instr(1, tString,”1”) > 0 Then
wb.Worksheets(1).Range(“A” & r).Value = tString
r=r+1
End If

Next p
.Close

End With

wrdApp.Quit
Set wrdDoc = Nothing
Set wrdApp = Nothing
wb.Saved = True

End Sub

To copy the above code to your file,

  • Press Alt + F11 on the keyboard
  • On the left hand side, you will see Microsoft Excel Objects
  • Right click and select Insert
  • Then click on Module
  • Copy the code to the code window on the right

Now lets see how this code works –

First we declare the variables we need –tstring as a string to hold text (we will see what text later). 2 variables “p” & “r” as counters.  These are of the “long” type.  Then we have the 2 object variables wrdApp and wrdDoc.  wrdApp is the word application object and wrdDoc is the Word document object.  Wb is our workbook variable for the new workbook which is created in the code.  If you are opening an existing workbook, you can assign this variable to that instead. The last variable is the trange variant type of variable which will have the contents that need to be transferred from the word doc to the excel file.

Set wb = Workbooks.Add

This assigns the new workbook to the wb variable.  If you do not want to add a new workbook but open an existing workbook, then you can alter this line as follows – 
Set wb – Workbooks.Open(“B:TestFile1.xlsx”)

With wb.Worksheets(1).Range(“A1”)
.Value = “Word Document Contents:”
.Font.Bold = True
.Font.Size = 14
.Offset(1,0).Select
End With

The With wb.Worksheets(1).range(“A1”) is a quick way of referencing it.  So you do not have to repeat it for each of the code lines between the With and End with statements.

These lines of code put in the text “Word Document Contents:” with a bold font and font size 14 in cell A1 of the 1st worksheet in the new workbook.  And then .Offset(1,0).Select selects the next row.

r = 3

The variable “r” is assigned a value 3 as this is the starting row in the excel file for the data to be copied from the word document.

Set wrdApp = CreateObject(“Word.Application”)

If Word is already running in your system,CreateObject will create a new instance of Word.  So this line assigns the object variable wrdApp to the Word Application which you can use later in the code.

wrdApp.Visible = True

The newly created instance of Word will not be visible when its being created.  To make it visible, you need to set wrdApp.Visible = True so that its visible.

Set wrdDoc = wrdApp.Documents.Open(«B:TestMyNewWordDoc.docx»)

We created the new instance of the word application but we haven’t opened a source word document yet.  So this command will open the word document.  The object wrdDoc has been assigned to this document so we can use it later in the code.

With wrdDoc….End With

This is our “With” loop which will work entirely with the wrdDoc object.  Once you open this loop, you do not have to repeat the text “wrdDoc” again in this loop.  You can directly start with the dot (“.”) before any objects relating to wrdDoc.  This loop ends with the End With statement.  Once the End With statement has been input, you cannot refer to the objects after wrdDoc with just the “.”.

For p = 1 to .Paragraphs.Count

This is the “For” loop which will loop from the 1st to last paragraphs in the word document.  The word file which contains the data has 100 lines of information, each stored as a separate paragraph.  The loop will increment from 1 to 100 and copy the paragraphs.  If certain conditions are set, the copy paste will be based on those conditions.

Set trange = .Range(Start:=.Paragraphs(p).Range.Start, End:=.Paragraphs(p).Range.End)

This assigns the start and end of each paragraph to range as the loop increments.

tString = trange.text
tString = Left(tString,len(tString)-1)

First the text from trange is passed on to TString.  Then each paragraph has a paragraph character at the end of the sentence.  This is removed using the Left function.  From the left side, all characters except the last one is stored in the tString variable.

If Instr(1, tString, “1”) > 0 Then
wb.Worksheets(1).Range(“A” & r).Value = tString
r=r+1
End If

This IF function checks if the text in tString contains the number 1.  If it is true, then it copies the contents of tString to the next available row in the workbook.  “r” first had a value of 3.  Using r=r+1, we increment it by 1, so that the next entry can be placed below the previous entry.

Next p
.Close

The Next p line of code increments to the next paragraph.

.Close closes the document once all the paragraphs have been worked on. This is the output we get in the excel file –

img1

You will see that only those paragraphs which contain number 1 anywhere in the number are included in the output.

wrdApp.Quit
Set wrdDoc = Nothing
Set wrdApp = Nothing
wb.Saved = True

wrdApp.Quit will close the word Application.  Set wrdDoc = Nothing and Set wrdApp = Nothing will release the memory taken by these 2 object variables and set them to Nothing.  wb.Saved = True will save the workbook.

With above code we can control which data to be copied from word file to excel file.

image 48

Понравилась статья? Поделить с друзьями:
  • Vba for microsoft excel 2010
  • Vba open excel file from excel
  • Vba for microsoft excel 2007
  • Vba omath to word
  • Vba for hyperlink in excel