我有一个从 Excel 电子表格导入数据的 Word 文档。两个文件都不是我的;我继承了这个问题。在 Excel 电子表格的先前版本中,数据位于 Q 到 T 列中。在新版本中,它位于 R 到 U 列中。使用的代码如下。当我运行文档的早期版本时,没有问题。一旦我使用新文档进行导入,它就会因以下错误代码而中断:
5941 - The requested member of the collection does not exist
调试器突出显示代码
ElseIf cel.Value <> ""
作为问题。新代码如下。 (工作的旧代码完全相同,但上述范围除外)。有什么想法吗?
提前致谢。
Sub ImportComplianceResults()
Dim fd As FileDialog, oApp As Excel.Application, oWb As Excel.Workbook, iWs As Integer, rData As Excel.Range
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
'Open modal window
.Title = "Select file to import:"
.InitialFileName = "X:\Template\"
.Filters.Clear
.Filters.Add "Excel files", "*.xlsx"
.InitialView = msoFileDialogViewList
.AllowMultiSelect = False
If .Show = -1 Then
Set oApp = New Excel.Application
Set oWb = oApp.Workbooks.Open(.SelectedItems(1), , True)
'Check for worksheet in selected file
For Each ws In oWb.Worksheets
If ws.Name = "Compliance Results" Or ws.Name = "Résultats de conformité" Then iWs = ws.Index
Next ws
If iWs > 0 Then
Set rData = oWb.Worksheets(iWs).Range("R10:T10,R13:U15,R17:U17,R19:U19,R21:U21,R23:U23,R25:U25,R27:U27,R29:U29,R32:U34,R37:U39")
With ActiveDocument
For Each cel In rData
If IsError(cel.Value) Then
.SelectContentControlsByTag(cel.Address).Item(1).Range.Text = "#N/A"
***ElseIf cel.Value <> "" Then
.SelectContentControlsByTag(cel.Address).Item(1).Range.Text = Format(cel.Value, cel.NumberFormat)***
Else
.SelectContentControlsByTag(cel.Address).Item(1).Range.Text = " "
End If
Next cel
End With
MsgBox "Data imported successfully.", vbInformation
Else
MsgBox "No data exists in selected file." & vbCr & "Import cancelled.", vbCritical
End If
oWb.Close False
'Cleanup Resources
Set rData = Nothing
Set oWb = Nothing
Set oApp = Nothing
Else
MsgBox "Import cancelled.", vbCritical
End If
End With
End Sub
最佳答案
尝试使用:
ElseIf Not cel.Value = "" Then
.SelectContentControlsByTag(cel.Address).Item(1).Range.Text = Format(cel.Value, cel.NumberFormat)
关于excel - Word 2010 宏不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46916781/