宏仅在活动工作表中开始

问题描述 投票:0回答:1

我是excel VBA的新手。我在互联网上找到一个宏,很好地解决了我的问题。但是,这个宏仅在活动工作表上运行仍然存在一个小问题。我想在指定的工作表上运行它(例如sheet1)。我把这个宏放在这里,请指导我解决这个问题。

Sub SelectByValue(Rng1 As Range, TargetValue As String)

Dim MyRange As Range
Dim Cell As Object

    'Check every cell in the range for matching criteria.

    For Each Cell In Rng1
        If Cell.Value > TargetValue Then
            If MyRange Is Nothing Then
                Set MyRange = Range(Cell.Address)
                Else
                Set MyRange = Union(MyRange, Range(Cell.Address))
            End If
        End If
    Next

    'Select the new range of only matching criteria

 MyRange.Select


End Sub

Sub CallSelectByValue()

    'Call the macro and pass all the required variables to it.
    Call SelectByValue(Range("A1:D500"), "")

End Sub
excel vba spreadsheet
1个回答
0
投票

您可以尝试在Sub CallSelectByValue()中建立图纸选择吗?

我自己还不是专业人士,但是这里有一个coupla建议:

1。在CallSelectByValue Sub中定义工作表(复制您的代码并对其进行编辑:)

Sub CallSelectByValue()

Dim Sheet as WorkSheet
Set Sheet = Sheets("Sheet1") 'insert relevant sheet name

'Call the macro as before, but include the sheet reference in the range
Call SelectByValue(Sheet.Range("A1:D500"), "")

End Sub

2。每次输入所需的图纸(当在不同的图纸上重复使用该子图时)

Sub CallSelectByValue()

    'Find out what sheet to refer to
    Dim SheetName As String
    Dim Sheet As Worksheet
    FindSheetName:
    SheetName = InputBox("Please enter the name of the sheet you'd like it to refer to", "Sheet Selection")

'Check the typed value is actually a sheet name
    If IsEmpty(Sheets(SheetName)) Then
        MsgBox "That sheet couldn't be found. Try again", vbOkOnly+vbCritical, "Sheet not found"
        GoTo FindSheetName 'loops you back to re-try typing it in
    Else
'If it matches up, assign that value to the Sheet variable
        Sheet = Sheets(SheetName)
    End If


    'Call the macro and pass all the required variables to it, including the sheet reference
    Call SelectByValue(Sheet.Range("A1:D500"), "")

End Sub

尝试这些,让我知道它们是否有效。

© www.soinside.com 2019 - 2024. All rights reserved.