1

我在 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

对我不起作用,有什么建议吗?工作簿打开正常,只是无法将数据放入其中。

4

1 回答 1

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
于 2013-04-21T09:44:35.337 回答