简体   繁体   中英

Why am I getting this runtime error?

very new at coding and first post on here. I have searched all over the place but could not figure out what is wrong with my code. Basically I am trying to calculated some averages from data on another workbook. The error that I get when I run the following code "Runtime error 1004, Application-defined error or method-defined error" seems to be generated from the line where I reference to the other workbook in order to carry out the Match method. It looks like it should work for me but the error says otherwise... Thanks for your help

Private Sub CommandButton1_Click()
Dim wbk As Workbook
Set wbk = Workbooks.Open("X:\Data Analysis\Process & Wall Loss Data Analysis\***** CT 12 HR AVG rev2.xlsm")
Dim nrow As Integer, conv_start As Double, conv_end As Double, avg1 As Double, avg2 As Double
nrow = Cells(9, 12)
For i = 1 To nrow
    conv_start = Application.VLookup(Cells(14 + i, 12), Range(Cells(3, 2), Cells(300, 3)), 2, True)
    conv_end = Application.VLookup(Cells(14 + i, 13), Range(Cells(3, 2), Cells(300, 3)), 2, True)
    avg1 = Application.Match(conv_start, wbk.Worksheets("PC & Wear").Range(Cells(1, 1), Cells(626, 1)), 1)
    avg2 = Application.Match(conv_end, wbk.Worksheets("PC & Wear").Range(Cells(1, 1), Cells(626, 1)), 1)
    For j = 1 To 40
        Cells(42 + j, 11 + i) = Application.Average(Range(Cells(avg1, 1 + j), Cells(avg2, 1 + j)))
    Next j
Next i

End Sub

wbk.Worksheets("PC & Wear").Range(Cells(1, 1), Cells(626, 1))

Here Cells() will refer to the activesheet, not to the sheet in the other workbook, so the code will fail whenever "PC & Wear" is not the active sheet.

You should fully-qualify all uses of Range() and Cells() with a worksheet object:

Dim sht As Worksheet
Set sht = wbk.Worksheets("PC & Wear")
'...
avg1 = Application.Match(conv_start, sht.Range(sht.Cells(1, 1), sht.Cells(626, 1)), 1)
'...

Note it's best to do this even for cases where you expect to use the ActiveSheet - later on you may develop your code further and end up with some other sheet being active, and your code will break (or worse, it will still work but produce wrong output).

A further improvement would be to define a range variable to avoid repeating yourself:

Dim rngLU As Range
Set rngLU  = wbk.Worksheets("PC & Wear").Range("A1:A626")
'...
avg1 = Application.Match(conv_start, rngLU, 1)
'...

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