循环工作表并设置值

时间:2018-02-19 06:47:30

标签: excel vba excel-vba loops

我正在编写工作表名称,并从该工作表中分配它前面的进度(相邻单元格)。

假设工作表名称为sheet1,sheet2 ... 我正在努力写

Sheet1 B50 of sheet1 Sheet2 B50 ofsheet2

Sub LoadSummarySheet()
Dim row, i, col As Integer
row = 5
col = 3
Range("C5:C15").ClearContents
For i = 1 To Sheets.Count
    If Application.Sheets(i).Name <> "TRACKER" And Application.Sheets(i).Name <> "Sheet1" And Application.Sheets(i).Name <> "PROGRESS" Then
        Cells(row, col).Value = Application.Sheets(i).Name
        row = row + 1
        Range(Cells(row, col + 1)).Value = Application.Sheets(i).Range("B50").Value
    End If
Next

1 个答案:

答案 0 :(得分:1)

也许你是在追求这样的事情(评论中的解释)

Sub LoadSummarySheet()
    Dim row As Long, col As Long
    row = 5
    col = 3

    Range("C5:C15").ClearContents

    Dim forbiddenNames As String
    forbiddenNames = "TRACKER,Sheet1,Sheet2,PROGRESS" 'list sheet names you don't want to be processed

    Dim sht As Worksheet
    For Each sht In Worksheets 'loop through currently active workbook sheets
        If InStr(forbiddenNames, sht.Name) = 0 Then 'if current sheet name is not "forbidden"
            Cells(row, col).Value = sht.Name
            row = row + 1
            Cells(row, col + 1).Value = sht.Range("B50").Value
        End If
    Next
End Sub

所有这些都假定当摘要表是活动表时正在运行宏

如果情况不是这样,那么您可以保证在适当的表格中写下如下:

Sub LoadSummarySheet()
    Dim row As Long, col As Long
    row = 5
    col = 3

    Range("C5:C15").ClearContents

    Dim forbiddenNames As String
    forbiddenNames = "TRACKER,Sheet1,Sheet2,PROGRESS" 'list sheet names you don't want to be processed

    Dim sht As Worksheet
    With Worksheets("TRACKER") ' reference wanted "summary" sheet (change TRACKER" to your actually "summary" sheet name)
        For Each sht In Worksheets 'loop through currently active workbook sheets
            If InStr(forbiddenNames, sht.Name) = 0 Then 'if current sheet name is not "forbidden"
                .Cells(row, col).Value = sht.Name ' preface a dot (.) to reference referenced object (i.e. 'Worksheets("TRACKER")' in this case)
                row = row + 1
                .Cells(row, col + 1).Value = sht.Range("B50").Value ' preface a dot (.)
            End If
        Next
    End With
End Sub