Excel VBA Run-time error '424': Object Required when trying to copy TextBox

前端 未结 3 1612
心在旅途
心在旅途 2021-02-10 09:08

I\'m attempting to copy the contents of a text box from one workbook to another. I have no problem copying cell values from the first workbook to the

3条回答
  •  太阳男子
    2021-02-10 09:19

    The problem with your macro is that once you have opened your destination Workbook (xlw in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.

    Sub UploadData()
        Dim xlo As New Excel.Application
        Dim xlw As New Excel.Workbook
        Dim myWb as Excel.Workbook
    
        Set myWb = ActiveWorkbook
        Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
        xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
        xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text
    
        xlw.Save
        xlw.Close
        Set xlo = Nothing
        Set xlw = Nothing
    End Sub
    

    If you prefer, you could also use myWb.Activate to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).

提交回复
热议问题