[英]Error with find and activate functions in excel with vba
我現在很難理解我為什么會得到我不該出現的錯誤。 我正在使用Office2007。在Excel中有兩張紙,分別是“ Ver”和“ Encargado”。在“ Ver”紙中,我有一個單元格,其中要輸入數字,然后按一個按鈕。 按鈕內的代碼是:
Private Sub CommandButton1_Click()
Dim buscar As Range
dato = Range("b2").Value
If dato = "" Then Exit Sub
Sheets("Encargado").Select
Set buscar = Range("b2:b12").Find(What:=dato, LookIn:=xlFormulas, SearchOrder:=xlByRows)
If Not buscar Is Nothing Then
buscar.Activate
ActiveCell.Offset(, -1).Copy Destination:=Ver.Cells(4, 2)
Sheets("Ver").Select
Else
Sheets("Ver").Select
MsgBox "Encargado no encontrado"
Exit Sub
End If
End Sub
在“ Encargado”表中,在b2:b12范圍內,只有數字beetwen 101和111,當我將數字117作為輸入時(例如),我認為它應該進入else部分,因為它不應該具有發現了任何巧合,但它進入了if部分,為什么呢? 我收到一條錯誤消息:“錯誤激活了范圍范圍錯誤”(您注意到我在西班牙語中使用Office,並使用西班牙語變量進行編程)。 當我逐行運行時,錯誤出現在“ buscar.Activate”行中。 有人知道錯誤在哪里嗎? 如果您要查看它,請參見以下文件: https : //www.dropbox.com/s/j1b39fqy971n7lf/Todo.xlsm謝謝。
您尚未在find函數中定義工作表,因此未定義工作表的參考工作表。 使用此代碼。
Private Sub CommandButton1_Click()
Dim buscar As Range
'Application.ScreenUpdating = False
dato = Range("b2").Value
If dato = "" Then Exit Sub
Set buscar = Sheets("Encargado").Range("b2:b12").Find(What:=dato, LookIn:=xlValues, SearchOrder:=xlByRows)
If Not buscar Is Nothing Then
'Encargado.Cells.Find(What:=Ver.Cells(2, 2), After:=Range("b2"), LookIn:=xlFormulas, SearchOrder:=xlByRows).Select
'desplazamiento en fila, desplazamiento en columna, positivo: hacia abajo, hacia la derecha
'buscar.Activate
c = buscar.Row
Sheets("Encargado").Range("a" & c).Copy
Sheets("Ver").Range("b4").PasteSpecial
Else
Sheets("Ver").Select
MsgBox "Encargado no encontrado"
Exit Sub
End If
'Application.ScreenUpdating = True
End Sub
編輯:如在下面的注釋中指出, Range
對象確實有一個.Activate
方法: http : //msdn.microsoft.com/zh-cn/library/office/ff837085( .Activate
.aspx
以下內容應該帶您前往目的地,但出於好奇–您是否研究了Excel的內置buscar
是一個
Range
對象,它沒有
Activate
方法。
=VLOOKUP
功能? 這可能使您不必在這里要求VBA ...
Option Explicit
Private Sub CommandButton1_Click()
Dim TerritorioNum As Long, LastRow As Long
Dim TerritorioRange As Range, FoundRange As Range
Dim VerSheet As Worksheet, EncSheet As Worksheet
'set references up-front
Set VerSheet = ThisWorkbook.Worksheets("Ver")
Set EncSheet = ThisWorkbook.Worksheets("Encargado")
With EncSheet
LastRow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Set TerritorioRange = .Range(.Cells(1, 1), .Cells(LastRow, 2))
End With
TerritorioNum = VerSheet.Cells(2, 2).Value
'find the territory number
Set FoundRange = TerritorioRange.Find(TerritorioNum)
If FoundRange Is Nothing Then
MsgBox ("Encargado no encontrado")
Exit Sub
Else
VerSheet.Cells(4, 2) = EncSheet.Cells(FoundRange.Row, FoundRange.Column - 1).Value
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.