Excel VBA使用单元格和范围函数中的variables
我在整个使用的单元格中find“例子”这个词。 但是,代码给我运行时错误1004“应用程序定义或对象定义的错误”。 我知道Range(Cells(1, 1), Cells(lastrow, lastcolumn))
什么问题。
提前致谢。 代码如下:
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
尝试这个。 当macros运行时,如果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")
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