循环工作簿,并将工作表名称放在一列中,而不跳过数据表上的行

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

我有这段代码,我不明白行计数器条目,但我认为它应该只填充空单元格。我只需要它从 I1 开始,并填充条目,另一个 if 循环需要将 K1 填充到末尾。

           Dim rowCounter As Integer
   

            
            Set dataSheet = ThisWorkbook.Worksheets("Data")

           
            
            ' Clear previous entries in columns I and K
            dataSheet.Range("I:I, K:K").ClearContents
            
  
            ' Loop through all worksheets
            For Each ws In ThisWorkbook.Worksheets
                rowCounter = rowCounter + 1
                
                If Right$(ws.Name, 3) = "MAP" Then
                    ' Write the sheet name to column K of the "Data" sheet
                    dataSheet.Cells(rowCounter, "K").Value = ws.Name
          
                End If
        
                        ' Check if any cell in column I contains a hyphen
                If InStr(1, ws.Name, "-", vbTextCompare) > 0 And Right$(ws.Name, 3) <> "MAP" Then
                    ' Write the sheet name to column I of the "Data" sheet
                    While Not dataSheet.Cells(rowCounter, "I").Value = "" 'ws.Name
                        rowCounter = rowCounter + 1
                    Wend
                    dataSheet.Cells(rowCounter, "I").Value = ws.Name

                    End If
                    
                    'Check if the sheet name is in the list to hide
                If IsError(Application.Match(ws.Name, sheetNamesToHide, 0)) Then
                 'Sheet names not found in the list, so not hidden
                Else
                    ws.Visible = xlSheetHidden
                End If
                        
            Next ws

我需要填写从 I1 和 K1 开始的数据列表。该代码跳过前 20 行,然后添加 3-4 个条目,然后再跳过 10 个单元格并添加更多单元格。

excel vba loops range
2个回答
0
投票

您已将计数器放在错误的位置,并且它正在跳过循环通过未填充的工作表名称的行。 我想你应该有这样的东西:

Sub FillData()

    Dim rowCounterI As Integer
    Dim rowCounterK As Integer
    Dim ws As Worksheet
    Dim dataSheet As Worksheet
    Dim sheetNamesToHide As Variant

    ' Initialize row counters
    rowCounterI = 1
    rowCounterK = 1

    ' Set the data sheet
    Set dataSheet = ThisWorkbook.Worksheets("Data")

    ' Clear previous entries in columns I and K
    dataSheet.Range("I:I, K:K").ClearContents

    ' Loop through all worksheets
    For Each ws In ThisWorkbook.Worksheets
        
        ' Check if the sheet name contains a hyphen but is not a "MAP" sheet
        If InStr(1, ws.Name, "-", vbTextCompare) > 0 And Right$(ws.Name, 3) <> "MAP" Then
            ' Write the sheet name to column I
            dataSheet.Cells(rowCounterI, "I").Value = ws.Name
            rowCounterI = rowCounterI + 1
        End If

        ' Check if the sheet name ends with "MAP"
        If Right$(ws.Name, 3) = "MAP" Then
            ' Write the sheet name to column K
            dataSheet.Cells(rowCounterK, "K").Value = ws.Name
            rowCounterK = rowCounterK + 1
        End If
        
        ' Check if the sheet name should be hidden
        If Not IsError(Application.Match(ws.Name, sheetNamesToHide, 0)) Then
            ws.Visible = xlSheetHidden
        End If

    Next ws

End Sub

0
投票

列出和隐藏工作表

enter image description here

Sub ListAndHide()
    
    ' Define constants.
    
    Dim NAMES_OF_SHEETS_TO_HIDE As Variant:
    NAMES_OF_SHEETS_TO_HIDE = Array("Sheet2", "Sheet3-MAP")
    Dim SRC_SHEET_NAME_PATERNS() As Variant:
    SRC_SHEET_NAME_PATERNS = VBA.Array("*MAP", "*-*")
    Const TGT_SHEET_NAME As String = "Data"
    Dim TGT_SHEET_COLUMNS() As Variant:
    TGT_SHEET_COLUMNS = VBA.Array("K", "I")
    ' Note: 'SRC_SHEET_NAME_PATERNS' must have the same number of elements
    '       as 'TGT_SHEET_COLUMNS'.
    
    ' Reference the workbook (right after the constants).

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    ' Reference the target sheet, the one being written to.

    Dim tws As Worksheet: Set tws = wb.Sheets(TGT_SHEET_NAME)
    
    ' Declare a counter variable to be used to loop through the elements
    ' of the arrays holding the source sheet patterns, the target sheet columns,
    ' and the target current rows, all at the same time.
    
    Dim u As Long
    
    ' Clear the contents of the target columns.
    
    Dim Upper As Long: Upper = UBound(SRC_SHEET_NAME_PATERNS)
    
    For u = 0 To Upper
        tws.Columns(TGT_SHEET_COLUMNS(u)).ClearContents
    Next u
        
    ' Define an array of the same size as the size of the source sheet patterns
    ' or the target sheet columns. Each element will hold the current
    ' (target) row in each target column.
        
    Dim tRows() As Long: ReDim tRows(0 To Upper)
        
    ' Loop through the sheets and apply the required logic...
    
    ' Declare additional variables.
    Dim sws As Worksheet, SheetNameIndex As Variant, dRow As Long
    Dim sSheetName As String, IsPatternMatched As Boolean
    
    ' Loop.
    For Each sws In wb.Worksheets
        ' Set.
        sSheetName = sws.Name
        IsPatternMatched = False ' reset
        ' If the sheet name matches a pattern, write it to the target sheet.
        For u = 0 To Upper
            ' Note: This comparison is case-sensitive i.e. 'A <> a'.
            If sSheetName Like SRC_SHEET_NAME_PATERNS(u) Then ' match
                tRows(u) = tRows(u) + 1
                tws.Cells(tRows(u), TGT_SHEET_COLUMNS(u)).Value = sSheetName
                IsPatternMatched = True
                Exit For
            'Else ' not a match; do nothing
            End If
        Next u
        ' Note: Think of the previous loop as if it were the 'Case' clauses
        '       of a 'Select Case' statement while the following 'If' statement
        '       as the 'Case Else' clause.
        ' In case you want to do something when the sheet name
        ' doesn't match any patterns.
        If Not IsPatternMatched Then
            Debug.Print "Sheet """ & sSheetName _
                & """ matches none of the patterns (""" _
                & Join(SRC_SHEET_NAME_PATERNS, """, """) & """)."
        End If
        ' Check if the sheet name is in the list of sheets to hide.
        ' Note: This happens whether a pattern was matched or not.
        ' Note: This search ('Match') is case-insensitive i.e. 'A = a'
        SheetNameIndex = Application.Match( _
            sSheetName, NAMES_OF_SHEETS_TO_HIDE, 0)
        If IsNumeric(SheetNameIndex) Then
            Debug.Print "Hiding sheet """ & sSheetName & """."
            sws.Visible = xlSheetHidden
        'Else ' sheet name not found in the list
            ' Either do nothing...
            ' ... or unhide:
            'sws.Visible = xlSheetVisible
        End If
        
    Next sws
    
    ' Inform.
    
    MsgBox "Sheets listed and hidden.", vbInformation

End Sub

立即窗口中的结果 (Ctrl+G)

Sheet "Data" matches none of the patterns ("*MAP", "*-*").
Sheet "Sheet2" matches none of the patterns ("*MAP", "*-*").
Hiding sheet "Sheet2".
Hiding sheet "Sheet3-MAP".
© www.soinside.com 2019 - 2024. All rights reserved.