Home » excel » Editing Cells in an Excel file opened through Word VBA

Editing Cells in an Excel file opened through Word VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m looking to create an excel document through Word VBA and edit some of the cells in it. I would like to be able to open a word document in a directory with other word documents and run a macro that loops through all of the documents and places the word document’s name in the ‘A’ column and the document’s flesch readability ease score in the ‘B’ column. I am currently able to create the excel document and save it to the directory at the end, but I am unable to edit any of the cells in the workbook itself. The code I currently have is below.

Dim objExcel
Dim objDoc
Dim objSelection
Dim myCellA
Dim myCellB
Dim SaveAs1 As String
Dim i As Integer

SaveAs1 = ActiveDocument.Path & "\FleschData"

Set objExcel = CreateObject("Excel.Application")
Set objDoc = objExcel.Workbooks.Add

objExcel.Visible = True

Set objSelection = objExcel.Selection

Dim directoryName1 As String

directoryName1 = ActiveDocument.Path & "\"
vFile = Dir(directoryName1 & "*.*")

i = 1

Do While vFile <> ""

        Set oDoc = Documents.Open(FileName:=directoryName1 & vFile)

        Dim CopyName() As String
        CopyName = Split(ActiveDocument.Name, ".")

        Set myCellA = objSelection.Tables(1).Cell(Row:=i, Column:=1)
        myCellA.Value = CopyName(0)

        Set myCellB = objSelection.Tables(1).Cell(Row:=i, Column:=2)
        myCellB.Value = ActiveDocument.Content.ReadabilityStatistics(9).Value

        i = i + 1
        oDoc.Close SaveChanges:=False
        vFile = Dir
Loop

objExcel.ActiveWorkbook.SaveAs FileName:=SaveAs1, CreateBackup:=False
Application.DisplayAlerts = True

The problem I’m having currently is at the ‘Set myCellA = objSelection.Tables(1).Cell(Row:=i, Column:=1)’ line and the error is “Object doesn’t support this property or method.” I have tried a couple different objects to call excel functions on but can’t seem to figure it out. I’m relatively new to VBA so any insight would be helpful.

How to&Answers:

Excel ranges don’t work like Word – the approach is quite different.

Untested:

Dim objExcel
Dim objWb
Dim objSelection
Dim myCellA
Dim myCellB
Dim SaveAs1 As String
Dim i As Integer

SaveAs1 = ActiveDocument.Path & "\FleschData"

Set objExcel = CreateObject("Excel.Application")
Set objWb = objExcel.Workbooks.Add
objExcel.Visible = True

Dim directoryName1 As String

directoryName1 = ActiveDocument.Path & "\"
vFile = Dir(directoryName1 & "*.*")

i = 0
Do While vFile <> ""
    i = i + 1
    Set oDoc = Documents.Open(Filename:=directoryName1 & vFile)
    With objWb.Sheets(1)
            .Cells(i, 1).Value = Split(oDoc.Name, ".")(0)
            .Cells(i, 2).Value = oDoc.Content.ReadabilityStatistics(9).Value
    End With
    oDoc.Close SaveChanges:=False
    vFile = Dir
Loop

objWb.SaveAs Filename:=SaveAs1, CreateBackup:=False
Application.DisplayAlerts = True