2017-03-08 84 views
1

我試圖在整個使用的單元格中找到「示例」一詞。但是代碼給了我運行時錯誤1004「應用程序定義或對象定義的錯誤」。我知道這條線有問題Range(Cells(1, 1), Cells(lastrow, lastcolumn)) 它可能是什麼?使用單元格和範圍函數中的變量的Excel VBA

在此先感謝。 這裏是代碼:

Dim lastrow as Long 
Dim lastcolumn as Long 
Dim sclnr as Range 
dim aws as WorkSheet 

Set aws = Thisworkbook.Sheets("Sheet1") 

'Using UsedRange 
lastrow = aws.UsedRange.Rows(aws.UsedRange.Rows.Count).Row 
lastcolumn = aws.UsedRange.Columns(aws.UsedRange.Columns.Count).Column 
'UsedRange works fine no problem with finding last row and column 

Set sclnr = aws.Range(Cells(1, 1), Cells(lastrow, lastcolumn)).Find("Example") 
'the word Example exits in one of the cells 
+0

是它的工作原理謝謝。 – MertTheGreat

+0

歡迎來到SO,請花一點時間參加[旅遊](點擊它),看看SO社區如何運作:接受答案和upvotes。 – R3uK

+0

請參閱[是。需要在.Cells中定義.Cells?](http://stackoverflow.com/questions/36368220/is-the-in-range-necessary-when-defined-by-cells) – Jeeped

回答

3

試試這個。如果在運行宏時aws不是活動工作表,則需要限定所有範圍/單元格引用。

Dim lastrow as Long 
Dim lastcolumn as Long 
Dim sclnr as Range 
dim aws as WorkSheet 

Set aws = Thisworkbook.Sheets("Sheet1") 

'Using UsedRange 
lastrow = aws.UsedRange.Rows(aws.UsedRange.Rows.Count).Row 
lastcolumn = aws.UsedRange.Columns(aws.UsedRange.Columns.Count).Column 
'UsedRange works fine no problem with finding last row and column 

Set sclnr = aws.Range(aws.Cells(1, 1), aws.Cells(lastrow, lastcolumn)).Find("Example") 
+0

它工作正常,我不能夠感謝你。它整天煩擾我。 – MertTheGreat

+1

我的榮幸。這是一個非常普遍的問題。 – SJR

+0

花點時間接受答案。 – ManishChristian

0
Sub test_MertTheGreat() 
Dim FirstAddress As String, LookForString As String 
LookForString = "Example" 

Dim LastRow As Long 
Dim LastColumn As Long 
Dim SclnR As Range 
Dim awS As Worksheet 

Set awS = ThisWorkbook.Sheets("Sheet1") 

'Using UsedRange 
With awS.UsedRange 
LastRow = .Rows(.Rows.Count).Row 
LastColumn = .Columns(.Columns.Count).Column 
End With 'awS.UsedRange 

Set SclnR = awS.Range(Cells(1, 1), Cells(LastRow, LastColumn)).Find("Example") 
'the word Example exits in one of the cells 

With awS.Range(awS.Cells(1, 1), awS.Cells(LastRow, LastColumn)) 
    .Cells(1, 1).Activate 
    'First, define properly the Find method 
    Set SclnR = .Find(What:=LookForString, _ 
       After:=ActiveCell, _ 
       LookIn:=xlValues, _ 
       LookAt:=xlWhole, _ 
       SearchOrder:=xlByColumns, _ 
       SearchDirection:=xlNext, _ 
       MatchCase:=False, _ 
       SearchFormat:=False) 

    'If there is a result, keep looking with FindNext method 
    If Not SclnR Is Nothing Then 
     FirstAddress = SclnR.Address 
     Do 
      '''---+++--- Your actions here ---+++--- 
      Set SclnR = .FindNext(SclnR) 
     'Look until you find again the first result 
     Loop While Not SclnR Is Nothing And SclnR.Address <> FirstAddress 
    End If 
End With 

End Sub 
相關問題