简体   繁体   中英

Runtime error 91 in Excel/VBA on assigning Workbook variable

I have this code in Creator workbook and I am copying data from the data file I select. But the code gives me the following error:

Object variable or with block variable not set

Sub transfer()
Dim myfile As Workbook
Dim myWs As Worksheet
Dim DataWs As Worksheet

Set myWs = ThisWorkbook.ActiveSheet

myfile = Application.GetOpenFilename(, , "Browse For Data file")
Workbooks.Open myfile
Set DataWs = myfile.Sheets("Instru Input")

myWs.Range("C3:C11000").Copy
DataWs.Range("E2").PasteSpecial xlPasteAll
myWs.Range("E3:E11000").Copy
DataWs.Range("F2").PasteSpecial xlPasteAll
myWs.Range("G3:G11000").Copy
DataWs.Range("G2").PasteSpecial xlPasteAll
myWs.Range("I3:I11000").Copy
DataWs.Range("H2").PasteSpecial xlPasteAll
myWs.Range("K3:K11000").Copy
DataWs.Range("I2").PasteSpecial xlPasteAll
myWs.Range("M3:M11000").Copy
DataWs.Range("J2").PasteSpecial xlPasteAll
myWs.Range("O3:O11000").Copy


ThisWorkbook.SaveAs

ThisWorkbook.Close

End Sub

This is what GetOpenFileName does by the specification from here :

Displays the standard Open dialog box and gets a file name from the user without actually opening any files.

Thus, once you get the file name (with the file path) as a string, it should be recorded as a string. Using this string, a workbook variable could be assigned with Set myWb = Workbooks.Open(fileName) :

Sub TestMe()

    Dim fileName As String
    fileName = Application.GetOpenFilename(, , "Browse For Data file")
    Debug.Print fileName

    Dim myWb As Workbook
    Set myWb = Workbooks.Open(fileName)

End Sub

In general, this is how a working code, taking some info from one worksheet to a worksheet in another workbook would look like:

Sub TestMe()

    Dim fileName As String
    fileName = Application.GetOpenFilename(Title:="Browse For Data file")
    Debug.Print fileName

    Dim targetWs As Worksheet
    Set targetWs = Workbooks.Open(fileName).Worksheets("Instru Input")

    Dim sourceWs As Worksheet
    'To avoid using the ActiveSheet:
    Set sourceWs = ThisWorkbook.Worksheets("NameOfTheWorksheet") 

    With sourceWs
        .Range("C3:C11000").Copy targetWs.Range("E2")
        .Range("E3:E11000").Copy targetWs.Range("F2")
        'And so on ...
    End With

    ThisWorkbook.SaveAs "WriteFileAddressHere.xlsb"
    ThisWorkbook.Close

End Sub

Make sure that you change "NameOfTheWorksheet" string and "WriteFileAddressHere.xlsb" to something relevant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM