2017-01-23 125 views
1

我的代碼段如下;Excel VBA - 查找函數 - 查找變量

Dim Column1 As String 
Worksheets("Graph").Activate 
Column1 = Cells(1, "P").Value 

Dim Column2 As String 
Worksheets("Graph").Activate 
Column2 = Cells(2, "P").Value 

Cells.Find(What:=Column1).Activate 
StartP3Column = ActiveCell.Column 

Cells.Find(What:=Column2).Activate 
StartP4Column = ActiveCell.Column 
EndP3Column = StartP4Column - 1 

Cells.Find(What:="End Column").Activate 
StartEndColumn = ActiveCell.Column 
EndP4Column = StartEndColumn - 1 

我試圖讓P1和P2中的值決定宏運行時選擇哪些列。因此,在第一個2 Cell.Find(What:=)函數中,我希望「Column1」獲取Column1變量(P1中的值)。

當我運行宏,我得到的錯誤「運行時錯誤:與塊變量未設置91.對象變量」,當我調試,問題是用線Cells.Find(What:=Column1).Activate

任何想法?

+0

可以把這個值被發現的?你需要檢查返回如此暗淡的範圍,設置r = find(),然後檢查返回r,如果它沒有發現它什麼都不是。然後,如果不是什麼r.activate,但只有在這個宏中激活P2的查找。你也不需要激活Graph兩次。 –

回答

0

如果你搜索的片Sheet1這些數據,這將運行:

Dim wsG As Worksheet 
Dim wsS As Worksheet 
Dim Rg As Range 
Dim Column1 As String 
Dim Column2 As String 
Set wsG = ThisWorkbook.Sheets("Graph") 
Set wsS = ThisWorkbook.Sheets("Sheet1") 

wsG.Activate 
Column1 = wsG.Cells(1, "P").Value 
Column2 = wsG.Cells(2, "P").Value 

Set Rg = wsS.Cells.Find(What:=Column1) 
If Not Rg Is Nothing Then 
    StartP3Column = Rg.Column 
Else 
    MsgBox Column1 & " not found in " & wsS.Name 
End If 

Set Rg = wsS.Cells.Find(What:=Column2) 
If Not Rg Is Nothing Then 
    StartP4Column = Rg.Column 
    EndP3Column = Rg.Column - 1 
Else 
    MsgBox Column2 & " not found in " & wsS.Name 
End If 

Set Rg = wsS.Cells.Find(What:="End Column") 
If Not Rg Is Nothing Then 
    StartEndColumn = Rg.Column 
    EndP4Column = Rg.Column - 1 
Else 
    MsgBox "End Column" & " not found in " & wsS.Name 
End If 
+0

嗨,我正在搜索的數據在不同的工作表上。我試過編輯你的腳本來查找其他工作簿中的值,但它沒有起作用,StartP3Column,StartP4Column等的值都是「空」,除了EndP4Column是30. – Dullspark

+0

@Dullspark:請參閱編輯! ;)您只需將'Sheet1'更改爲您正在搜索的工作表的名稱! ;) – R3uK

+0

我已經做到了,值仍然是空的:( – Dullspark