How to get the active word doc using xl vba
Hi forum
I have two arrays in word document, one is name and another is year.
What my need is to sort the arrays, first Chronologically and then alphabetically.
so i use excel macro to sort the arrays.
here, what i need is to print the sorted array in to active word document where we fetch the input array.
the below code for word
Code:
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("D:\sortingexcel.xls")
Set xlSheet = xlBook.ActiveSheet
For i = Val(I1) To Val(J1)
xlSheet.Cells(i, 1) = AuthorWithoutIntials(i)
Next i
For i = Val(I1) To Val(J1)
xlSheet.Cells(i, 2) = ReferenceYear(i)
Next i
xlSheet.Application.Visible = True
Const sPath As String = "D:\"
Const sFileName As String = "sortingexcel.xls"
Const sMacroName1 As String = "SortRange"
Const sMacroName2 As String = "PrintSortedNameYear"
Const sMacroName3 As String = "Clearcontents"
xlApp.Run sFileName & "!" & sMacroName1
xlApp.Run sFileName & "!" & sMacroName2
xlApp.Run sFileName & "!" & sMacroName3
where I1 and j1 are the lower & upper bounds of array.
The below code for excel
Code:
Sub PrintSortedNameYear()
Dim Ar1() As String, LastRow As Integer
Dim WrdApp As Object, WrdDoc As Object, WrdSel As Object
Call SortRange 'sort the range by call the sub
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
ReDim Ar1(1 To 2, 1 To LastRow) As String
For i = 1 To LastRow
Ar1(1, i) = Cells(i, "A") 'ReferenceAuthorName
Ar1(2, i) = Cells(i, "B") 'ReferenceYear
Next
Set WrdApp = CreateObject("Word.Application")
WrdApp.Visible = True
Set WrdDoc = WrdApp.ActiveDocument 'WrdApp.Documents.Add ' create a new word document
Set WrdSel = WrdApp.Selection
With WrdSel
For i = LBound(Ar1, 2) To UBound(Ar1, 2)
.TypeText Text:=Ar1(1, i) & " " & Ar1(2, i) & ","
Next
End With
Set WrdApp = Nothing
Set WrdDoc = Nothing
Set WrdSel = Nothing
End Sub
when setting the active document in excel code, it encounter an error in this line
Code:
Set WrdDoc = WrdApp.ActiveDocument
How could we declare the current active document in excel macro?
Kindly guide me to fix this bug.
Regards,
Re: How to get the active word doc using xl vba
Quote:
Set WrdApp = CreateObject("Word.Application")
WrdApp.Visible = True
Set WrdDoc = WrdApp.ActiveDocument
at this point you have opened word, but no document has been opened or added to the documents collection, so no activedocument, as i am sure is obvious in the visible word window