将数据从Excel表单传递到新的电子表格

我正在尝试Excel中的新function。 和VBA一样新,所以请耐心等待。

我有一个表格上有一堆东西在上面..一个项目是一个button,打开一个电子表格。 我想将表单中的信息传递给新打开的电子表格,但是却在墙上跑步。 我做了以下..

在窗体顶部声明一个公共variables

Public instno As String 

然后在表单的初始化我从当前工作表中分配一个值给这个string。

 Sub UserForm_Initialize() instno = Cells(ActiveCell.Row, "J").Value ' other stuff in here too, this is just for this problem... End Sub 

现在打开新工作簿的button的代码,我试图传递的值。

 Private Sub CMB2_Click() Dim xlApp As Excel.Application Set xlApp = CreateObject("Excel.Application") xlApp.Visible = True xlApp.Workbooks.Open Filename:="G:\tracking.xlsm" Cells(13, "E").Value = instno 'data should go into cell E13 End Sub 

不适合我,有什么build议吗? 该工作簿打开罚款,只是不能得到的数据。

如果你在Excel中这样做,那么你不需要每次都创build对象。 看到这个例子。 另外当你使用对象时,完全限定它们。

 Dim instno As String Sub UserForm_Initialize() Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("Sheet1") '~~> Though I am not in favor of `ActiveCell`. Use the actual cell address instno = ws.Range("J" & ActiveCell.Row).Value End Sub Private Sub CMB2_Click() Dim wb As Workbook Dim ws As Worksheet Set wb = Workbooks.Open(Filename:="G:\tracking.xlsm") '~~> Change this to the relevant worksheet Set ws = wb.Sheets("Sheet1") ws.Range("E13").Value = instno End Sub 

跟进

如果你想遵循CreateObject方式,那么试试这个

 Dim instno As String Sub UserForm_Initialize() Dim wsThis As Workbook Set wsThis = ThisWorkbook.Sheets("Sheet1") '~~> Though I am not in favor of `ActiveCell`. Use the actual cell address instno = ws.Range("J" & ActiveCell.Row) End Sub Private Sub CMB2_Click() Dim xlApp As Object, xlWb As Object, xlWs As Object Set xlApp = CreateObject("Excel.Application") xlApp.Visible = True Set xlWb = xlApp.Workbooks.Open(Filename:="G:\tracking.xlsm") '~~> Change this to the relevant worksheet Set xlWs = xlWb.Sheets("Sheet1") xlWs.Range("E13").Value = instno End Sub