【发布时间】:2019-07-11 19:12:42
【问题描述】:
是否可以选择从word到excel中提取哪些特定的表单控件?
我现在有一个宏,它可以正常工作,并将所有表单控件提取到 Excel 中,放在一行中。问题是,我需要将控件分解为 3 个不同的部分。每个都有自己的工作表/标签。表单控件是文本和下拉列表。
例如:假设表格有 9 个问题。
第一个工作表/标签,宏将提出问题 1. 2. 3.
第二个工作表/标签,宏会提出问题(我不介意单独的宏) 4. 5. 6.
第三个工作表/标签宏将提出问题(我不介意单独的宏) 7. 8. 9.
当前运行良好但引入了每个控件的宏:
Sub GetFormData()
'Note: this code requires a reference to the Word object model
Application.ScreenUpdating = False
Dim wdApp As New Word.Application, wdDoc As Word.Document, CCtrl As Word.ContentControl
Dim strFolder As String, strFile As String, WkSht As Worksheet, i As Long, j As Long
strFolder = GetFolder
If strFolder = "" Then Exit Sub
Set WkSht = ActiveSheet
i = WkSht.Cells(WkSht.Rows.Count, 1).End(xlUp).Row
strFile = Dir(strFolder & "\*.docx", vbNormal)
While strFile <> ""
i = i + 1
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
j = 0
For Each CCtrl In .ContentControls
With CCtrl
Select Case .Type
Case Is = wdContentControlCheckBox
j = j + 1
WkSht.Cells(i, j).Value = .Checked
Case wdContentControlDate, wdContentControlDropdownList, wdContentControlRichText, wdContentControlText
j = j + 1
WkSht.Cells(i, j).Value = .Range.Text
Case Else
End Select
End With
Next
.Close SaveChanges:=False
End With
strFile = Dir()
Wend
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing
Application.ScreenUpdating = True
End Sub
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function
外观示例。这些问题是重复的,所以不要介意:
【问题讨论】:
-
FWIW
Dim wdApp As New Word.Application是个坏主意。在Set wdApp = Nothing指令之后立即尝试Debug.Print wdApp Is Nothing,你会明白我的意思;-) -
总是三套三套吗?如果没有,您需要更准确地描述所需的逻辑......
-
@CindyMeister 不,不会一直在那里。第一组共12道题。第二组题共7题。第三组共8题
-
@MathieuGuindon 谢谢Mathieu,我按照你的建议做了,但没有发现任何区别。 ://
-
如果你尝试过
Debug.Print语句,即使在Set wdApp = Nothing之后,它也会打印出False。通常应避免使用自动实例化的对象变量,尤其是那些涉及产生新进程的变量。