设置等于行号的变量

时间:2018-02-09 17:18:33

标签: excel-vba vba excel

我需要将EndOfFile和DataRange =设置为它们所在的行号。

提前致谢,

斯科特

Dim NumOfRows As Integer
    Dim EndOfFile As Range
    Dim DataRange As Range 

Sub Find_xy_data()
    Dim RowArray(1 To 10000) As Range

    'Counters
    i = 2


       ' Locate last line of KLARF location data
    Cells.Find(What:="EndOfFile;", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False).Activate
    Set EndOfFile = ActiveCell.Rows



    ' Locate first line of KLARF location data
    Cells.Find(What:="DefectRecordSpec", After:=ActiveCell, LookIn:= _
        xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False).Activate
       Set DataRange = ActiveCell

2 个答案:

答案 0 :(得分:1)

以下内容如何:

Sub Find_xy_data()
    Dim ws As Worksheet: Set ws = Worksheets("Sheet1")
    'declare and set the worksheet above, amend as required

    Dim EndOfFile As Range
    Dim DataRange As Range

    Set EndOfFile = ws.Cells.Find(What:="EndOfFile;")
    'find and set variable to range at which it was found
    Set DataRange = ws.Cells.Find(What:="DefectRecordSpec")
    If Not EndOfFile Is Nothing Then MsgBox "EndOfFile found at row " & EndOfFile.Row
    'if variable is not empty then found, prompt with msgbox
    If Not DataRange Is Nothing Then MsgBox "DefectRecordSpec found at row " & DataRange.Row
End Sub

答案 1 :(得分:1)

首先你需要找到细胞 如果找不到行号,则无法返回行号或激活单元格;将发生错误。

Sub Test()

    Dim EndOfFile As Range

    Set EndOfFile = Sheet1.Cells.Find(What:="EndOfFile;", After:=ActiveCell, LookIn:= _
        xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False)

    If Not EndOfFile Is Nothing Then
        MsgBox EndOfFile.Address & " is on row " & EndOfFile.Row
    Else
        MsgBox "Not Found"
    End If

End Sub