使用"找到"值以定义新范围

时间:2017-08-04 16:57:45

标签: excel-vba vba excel

我正在尝试在VBA中创建一个动态宏,通过该宏我可以从标题为"位置编号"的列开始选择一个新范围。所以我的"程序"理想情况下转到工作表,找到我想要找到这个单元格的区域,该单元格显示"位置编号",找到它,给我列号(因为列可能会更改)然后从该列开始标记新范围并将其与另一个工作表进行比较。到目前为止,我一直困在我试图使用我发现的列号来定义新范围的部分。我尝试了很多我在网上找到的东西,但无法修复它。

错误已开启:

Set Range1 = Range("'C'& ColNum" & "R1")

我尝试了其他一些变种,但它不起作用或给我一个数字作为输出。

提前致谢!

Dim FilledRange As Range
Dim Range1 As Range
Dim Rng As Range
Dim ColNum As String

Worksheets("FILLED Today").Activate
Set FilledRange = Range("a1")
FilledRange.CurrentRegion.Select

Selection.Find(What:="Position Number", After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate

ColNum = ActiveCell.Column
MsgBox (ColNum)

Set Range1 = Range("'C'& ColNum" & "R1")
MsgBox (Range1)

1 个答案:

答案 0 :(得分:1)

使用单元格:

Set Range1 = Cells(1,Colnum)

应该避免.Select.Activate

Dim FilledRange As Range
Dim Range1 As Range
Dim Rng As Range
Dim findrng As Range
Dim ColNum As Long

With Worksheets("FILLED Today")
    Set FilledRange = .Range("A1").CurrentRegion

    Set findrng = FilledRange.Find(What:="Position Number", After:=.Range("A1"), LookIn:= _
        xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False)

    If Not findrng Is Nothing Then ' test to ensure it was found.
        ColNum = findrng.Column
        MsgBox ColNum

        Set Range1 = .Cells(1, ColNum)
        MsgBox Range1
    Else
        MsgBox "String not found in Range"
    End If
End With