简体   繁体   English

为什么会出现此运行时错误?

[英]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. 当我运行以下代码“运行时错误1004,应用程序定义的错误或方法定义的错误”时遇到的错误似乎是从我引用其他工作簿以执行Match方法的那一行生成的。 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. 在这里, Cells()将引用活动工作表,而不是其他工作簿中的工作表,因此,只要“ PC&Wear”不是活动工作表,代码就会失败。

You should fully-qualify all uses of Range() and Cells() with a worksheet object: 您应该使用工作表对象完全限定Range()Cells()所有用法:

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). 请注意,即使在您希望使用ActiveSheet的情况下,也最好这样做-稍后,您可能会进一步开发代码并最终使其他工作表处于活动状态,并且代码会中断(或更糟糕的是,它仍然可以工作,但是会产生错误的输出)。

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)
'...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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