我希望通过Word VBA创建一个excel文档并编辑其中的某些单元格。我希望能够与其他Word文档一起在目录中打开Word文档,并运行一个循环遍历所有文档的宏,并将该Word文档的名称放在“ A”列中,并将该文档的易读易读性得分置于“ B”列。目前,我可以创建excel文档并将其保存到目录的末尾,但是我无法编辑工作簿本身中的任何单元格。我当前拥有的代码如下。
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
我当前遇到的问题是在“设置myCellA = objSelection.Tables(1).Cell(Row:= i,Column:= 1)”行中,错误是“对象不支持此属性或方法。”我尝试了几个不同的对象来调用excel函数,但似乎无法弄清楚。我是VBA的新手,所以任何见解都会有所帮助。
答案 0 :(得分:2)
Excel范围不能像Word一样工作-方法完全不同。
未经测试:
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