我怎样才能使用单词的用户表单input数据以后插入到我的编码将打开的Excel文件

我有以下编码,我努力从我的用户表单input数据到我的代码将打开的Excel文件。 我已经尝试过在编码中允许代码继续,一旦我点击提交我的用户表单,但比它丢失数据或只是不input到我select的Excel文件。 因此,这不允许我从Excel中将必要的数据复制到我的Word文件中。

Sub Data() UserForm1.Show 'show the userform Dim exl As Object 'exl ist der Verweis auf Excel Dim oExl As Object Dim ImportDatei As Variant Set exl = CreateObject("excel.application") ImportDatei = exl.Application.GetOpenFilename(FileFilter:="Microsoft Excel-Dateien (*.xlsm), *.xlsm", Title:="Eine Datei auswählen") 'ab exl. wir der Excel Befehl angefügt If ImportDatei = False Then Exit Sub exl.Workbooks.Open (ImportDatei) exl.Visible = True 'Input data into the excel field exl.Range("C1").Select 'Select the cell exl.ActiveCell.FormulaR1C1 = TextBox1 'Insert the input Value in the cell exl.ActiveSheet.Range("$A$5:$D$65").AutoFilter Field:=1, Criteria1:="<>" ' Filtern ' Product (variante) copy and formating exl.Range("A1:A1").Copy Selection.PasteAndFormat (wdFormatPlainText) Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend Selection.Style = ActiveDocument.Styles("Heading 2") Selection.MoveDown Unit:=wdLine, Count:=1 Selection.InsertBreak Type:=wdLineBreak 'Insert line space ' Copy other relevant info exl.Range("A5:A7").Copy Selection.PasteAndFormat (wdFormatPlainText) Selection.InsertBreak Type:=wdLineBreak 'Copy table exl.Range("A8:D79").Copy Selection.Paste Selection.InsertBreak Type:=wdLineBreak Selection.InsertBreak Type:=wdLineBreak End Sub 

没有看到表单代码,我会说:

您将丢失该表单中保存的variables,因为像子或函数一样,其中的声明和分配只保存在本地。

例如,如果这个代码是在你的forms:

 Input_Button_Click() Dim This_String As String This_string = Textbox1.Value End Sub 

而另一个Sub,即使它在同一个模块内也是:

 Sub Show_Box_Text () MsgBox This_String End Sub 

将显示一个空的消息框。

那是因为This_String只在声明的Userform,Sub或Function范围内可用。

解决scheme1:从窗体代码中调用另一个子窗体,其forms参数如下:

 Input_Button_Click() Dim This_String As String This_string = Textbox1.Value Call Show_Text_Box(This_String) 'calls another sub or fucntion with argument This_String End Sub Sub Show_Box_Text (This_String as String) 'now requires to be called with 1 argument of type String, 'wich it will, for the duration of this sub refer to as This_String 'name in the calling sub doesnt need to match This_String MsgBox This_String End Sub 

将显示正确的值的文本框或:

解决scheme2:通过放置公共variables

 Public This_String as String 'now publicly available 

在“工作簿”或“文档”代码中

然后可以在工作簿/文档中的任何位置分配:

 Input_Button_Click() Thisworkbook.This_String = Textbox1.Value End Sub Sub Show_Box_Text () MsgBox Thisworkbook.This_String End Sub 

这些是IMO最容易解决您的问题的解决scheme。