简体   繁体   English

使用ThisWorkbook.Sheets(1)的Excel vba代码.Range不工作,但Sheet1.Range工作正常。 为什么?

[英]Excel vba code using ThisWorkbook.Sheets(1).Range not working, but Sheet1.Range works fine. Why?

When I use wb.Sheets(1).Range("A:A").Find(What:=ID, LookIn:=xlValues) I get error 91 - Object Variable or With Block not set. 当我使用wb.Sheets(1).Range("A:A").Find(What:=ID, LookIn:=xlValues)我得到错误91 - 对象变量或没有设置块。 When I use Sheet1.Range("A:A").Find(What:=ID, LookIn:=xlValues) it returns correct value. 当我使用Sheet1.Range("A:A").Find(What:=ID, LookIn:=xlValues)它返回正确的值。 Why the difference? 为什么不同?

Is there a flowchart I can reference or any simple information available to understand which sub-commands (I don't know the proper word) work with ThisWorkbook and Sheets(#) versus Sheet#.Whatever ? 是否有我可以参考的流程图或任何可用的简单信息,以了解哪些子命令(我不知道正确的单词)与ThisWorkbookSheets(#)Sheet#.Whatever什么?

I am hesitant to use Sheet("Name") because names might change later. 我对使用Sheet("Name")犹豫不决,因为名称可能会在以后更改。 I am using ThisWorkbook rather than ActiveWorkbook to keep all code attached to the appropriate workbook. 我使用ThisWorkbook而不是ActiveWorkbook来保持所有代码都附加到相应的工作簿。

Anything you can offer for simple reference info would be great. 您可以提供的任何简单参考信息都很棒。 I have researched, but still don't understand which sub-commands work with which parent commands. 我已经研究过,但仍然不明白哪些子命令适用于哪些父命令。 (Again, probably wrong terminology). (同样,可能是错误的术语)。

Private Sub lstExample_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    Dim wb As Workbook
    Dim I As Integer
    Dim ID As String
    Dim findValue As Range

    Set wb = ThisWorkbook
    'Get the values of the selected row in listbox on doubleclick
    For I = 0 To lstExample.ListCount - 1
        If lstExample.Selected(I) = True Then
    'Set listbox column 1 as ID value to find
            ID = lstExample.List(I, 1)
        End If
    Next I

    'Match ID (column A) on Sheet1
    Set findValue = wb.Sheets(1).Range("A:A").Find(What:=ID, LookIn:=xlValues)
    MsgBox findValue
End Sub

There is no difference between the properties of Sheets(1) and Sheet1 as long as both are the same object - Worksheet Object in your case. 只要两者都是相同的对象(在您的情况下为Worksheet对象),Sheets(1)和Sheet1的属性之间没有区别。

You're getting that error because findValue Is Nothing . 你得到那个错误,因为findValue Is Nothing That is, it couldn't find the ID in the column. 也就是说,它无法在列中找到ID。 When using the Find method, it's best to specify every argument. 使用Find方法时,最好指定每个参数。 Find remembers the last find you did, even if you did it in the UI and your using Find in VBA. 查找记住您上次查找的内容,即使您在UI中执行此操作并使用VBA中的查找也是如此。

For instance, if you check MatchCase in the UI when you do a Find. 例如,如果在执行查找时在UI中检查MatchCase。 Then you do a Find in VBA and don't specify the MatchCase property, it will use whatever you set the last time. 然后在VBA中执行查找并且不指定MatchCase属性,它将使用您上次设置的任何内容。

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

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