使用循环选择基于单元格值的特定工作表

时间:2017-08-08 07:49:06

标签: excel vba excel-vba

我是编程新手,我正在为公司完成一个小项目。我正在尝试编写循环遍历范围的代码,并且对于大于0的每个cell.value,它将找到相应的excel表并执行特定代码。谢谢!

Sub test()

Dim rng As Range, cell As Range

Set rng = Range("B3:B53")

For Each cell In rng
    If cell > 0 Then
        SheetName = ThisWorkbook.Sheets(cell.Value)
        ThisWorkbook.Sheets(SheetName).Select
        ActiveWindow.SelectedSheets.PrintOut Copies:=1
        Range("E4:P50").Select
        Selection.ClearContest
    End If
Next cell

End Sub

3 个答案:

答案 0 :(得分:0)

尝试

If cell > 0 Then
    dim ws as worksheet
    set ws = ThisWorkbook.Sheets(cell.Value)
    ws.PrintOut Copies:=1
    ws.Range("E4:P50").ClearContest
End If

答案 1 :(得分:0)

尝试:

Sub test()

Dim rng As Range, Cell As Range
Dim ws As Worksheet

Set rng = Sheets(1).Range("B3:B53")

On Error Resume Next
For Each Cell In rng
    If Cell.Value > 0 Then
        Set ws = Sheets(Cell.Value)
        If Not ws Is Nothing Then
            With ws
                .PrintOut Copies:=1
                .Range("E4:P50").ClearContents
            End With
        End If
    End If
Next Cell
End Sub

答案 2 :(得分:0)

希望这就是你要找的...... 一个简单的代码

Dim cell            As Range
Dim cell2           As Range
Dim cell3           As Range

    Set cell = Cells.Find(What:="Your Value", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    Set cell2 = Cells.Find(What:="Your Value", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    Set cell3 = Cells.Find(What:="Your Value", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then
    'Your code
Else
    'Your code
End If

If cell2 Is Nothing Then
    'Your code
Else
    'Your code
End If

If cell3 Is Nothing Then
    'Your code
Else
    'Your code
End If

您可以通过设置变量来添加更多单元格值。

如果您有任何疑问,请告诉我们。