我在Excel中尝试新功能。就像我对VBA一样新,所以请耐心等待。
我有一个包含大量内容的表单..一个项目是一个打开电子表格的按钮。我想将表单中的信息传递给新打开的电子表格,但我正在墙上运行。我做了以下......
在表单顶部声明了一个公共变量
Public instno As String
然后在表单初始化时,我从当前工作表中为该字符串赋值。
Sub UserForm_Initialize()
instno = Cells(ActiveCell.Row, "J").Value
' other stuff in here too, this is just for this problem...
End Sub
现在是打开新工作簿的按钮的代码,我正在尝试将值传递给。
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
对我不起作用,有什么建议吗?工作簿打开正常,无法将数据输入其中。
答案 0 :(得分:0)
如果您在Excel中执行此操作,则每次都不需要CreateObject
。看这个例子。此外,当您使用对象时,请完全限定它们。
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