English 中文(简体)
B. 非独特工作一览表
原标题:Combine non unique worksheets
  • 时间:2024-01-22 22:17:36
  •  标签:
  • excel
  • vba

我有一份有37个表格的工作手册。 每一表格每栏有37至60栏,每栏有头盔,然后是下行的数值。 浏览次数可能因我所研究的目前档案而异,只有17个区和6 181个区。 如果要把头盔和去除重复,所有表格都有189种不同的可能选择。 档案格式是我每星期拿到档案的,希望产出是一样的,因此,我用宏观方法帮助这里的某个人。 我过去几小时与查塔-GPT合作,试图使这项工作取得成功。 我想做的是,一个新的表格,称为“联合数据”,有189个不同的主人,然后从所有表格中逐个输入数据,其数值按标题逐项输入适当的栏目。 以下是在我宣布之前,Chata GPT来到我。

    Sub CombineTabs()
    Dim combinedSheet As Worksheet
    Dim originalSheet As Worksheet
    Dim header As Range
    Dim targetCol As Long

      Create a new sheet for the combined data
    Set combinedSheet = Sheets.Add(After:=Sheets(Sheets.Count))
    combinedSheet.Name = "CombinedData"

      Loop through all sheets in the original workbook
    For Each originalSheet In ThisWorkbook.Sheets
              Loop through each header in the Summary sheet
            For Each header In originalSheet.Range("A1:BI1")
                  Get the target column in the Combined sheet
                targetCol = targetCol + 1

                  Copy the header to the Combined sheet
                combinedSheet.Cells(1, targetCol).Value = header.Value

                  Copy the values from the original sheet to the Combined sheet
                Dim lastRowCombined As Long
                lastRowCombined = combinedSheet.Cells(combinedSheet.Rows.Count, targetCol).End(xlUp).Row

                combinedSheet.Cells(2, targetCol).Resize(originalSheet.UsedRange.Rows.Count - 1, 1).Value = originalSheet.Columns(header.Column).Value

                  Remove duplicates in the Combined sheet
                lastRowCombined = combinedSheet.Cells(combinedSheet.Rows.Count, targetCol).End(xlUp).Row
                combinedSheet.Range(combinedSheet.Cells(2, targetCol), combinedSheet.Cells(lastRowCombined, targetCol)).RemoveDuplicates Columns:=1, header:=xlNo
            Next header
    Next originalSheet
End Sub

法典没有错误,只是试图将表格放在综合数据表上,而不是所有数据都放在后面。 因此,我放弃了大赦国际的帮助,并转向了 st流的思想的共同智慧。

该项目的真正最终游戏是,一旦在单一表格中,我们将每星期将数据上载到KQ数据库,以便我们能够查询数据,并将数据添加到报告/仪表板上。

Edit1:为了回答某些问题,在任何一张单上都有重复的头盔,但在查阅不同表格时有重复。

最佳回答
  • Assuming there are no duplicate header names on each sheet.
Option Explicit

Sub Demo()
    Dim i As Long, j As Long
    Dim vKey, oDic, arrData, rngData As Range
    Dim arrRes, iR As Long, iC As Long, iRes As Long
    Dim LastRow As Long, LastCol As Long, ColCnt As Long
    Dim oSht As Worksheet, cbSht As Worksheet
    Const CB_SHT = "CombinedData"
    Const MAX_COL = 60   modify as needed
      Create CombinedData sheet
    On Error Resume Next
    Set cbSht = Sheets(CB_SHT)
    On Error GoTo 0
    If cbSht Is Nothing Then
        Set cbSht = Sheets.Add
        cbSht.Name = CB_SHT
    Else
        cbSht.Cells.Clear
    End If
    Set oDic = CreateObject("scripting.dictionary")
    iR = 2
      loop through worksheet
    For Each oSht In Worksheets
        If oSht.Name <> CB_SHT Then
            LastRow = oSht.Cells(oSht.Rows.Count, "A").End(xlUp).Row
            If LastRow > 1 Then
                LastCol = oSht.Cells(1, oSht.Columns.Count).End(xlToLeft).Column
                Set rngData = oSht.Range("A1", oSht.Cells(LastRow, LastCol))
                arrData = rngData.Value   load data into an array
                For j = LBound(arrData, 2) To UBound(arrData, 2)
                    If Not oDic.exists(arrData(1, j)) Then
                        oDic(arrData(1, j)) = oDic.Count + 1
                    End If
                Next
                ReDim arrRes(1 To UBound(arrData) - 1, 1 To oDic.Count)
                For j = LBound(arrData, 2) To UBound(arrData, 2)
                    iC = oDic(arrData(1, j))
                    For i = LBound(arrData) + 1 To UBound(arrData)
                        arrRes(i - 1, iC) = arrData(i, j)
                    Next
                Next
                  Write ouput to CombinedData sheet
                cbSht.Cells(iR, 1).Resize(UBound(arrRes), oDic.Count).Value = arrRes
                iR = iR + UBound(arrRes)
            End If
        End If
    Next
      Populate headers
    ReDim arrRes(0, 1 To oDic.Count)
    i = 0
    For Each vKey In oDic.Keys
        i = i + 1
        arrRes(0, i) = vKey
    Next
    cbSht.Cells(1, 1).Resize(1, oDic.Count).Value = arrRes
End Sub

“在座的影像描述”/

问题回答

Taller beat me to it but posting anyway...

Sub CombineTabs()
    Dim wsAll As Worksheet, wb As Workbook, ws As Worksheet, rngData As Range
    Dim header As Range, dict As Object, hdr As String, rwPaste As Long, lastRow As Long, lastCol As Long
    
    Set dict = CreateObject("scripting.dictionary")  for tracking unique headers
    dict.CompareMode = 1  vbTextCompare: case-insensitive

    Set wb = ActiveWorkbook
      Create a new sheet for the combined data
    Set wsAll = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.count))
    wsAll.Name = "CombinedData"
    rwPaste = 2  start pasting here

      Loop through all sheets in the original workbook
    For Each ws In wb.Sheets
        If ws.Name <> wsAll.Name Then
            lastRow = LastOccupiedRow(ws)
            lastCol = LastOccupiedColumn(ws)
            If lastRow > 1 Then   any data to copy?
                Set rngData = ws.Range("A1", ws.Cells(lastRow, lastCol))  all data
                For Each header In rngData.rows(1).Cells  loop over header row
                    hdr = header.Value
                    If Not dict.Exists(hdr) Then               new header?
                        dict.Add hdr, dict.count + 1           add to dictionary
                        wsAll.Cells(1, dict(hdr)).Value = hdr  add header to summary sheet
                    End If
                     copy data below header over to summary sheet
                    header.Offset(1).Resize(rngData.rows.count - 1).Copy _
                                           wsAll.Cells(rwPaste, dict(hdr))
                Next header
                rwPaste = rwPaste + lastRow - 1  increment destination row for next worksheet
            End If  any data to copy
        End If      not wsAll
    Next ws
End Sub

Function LastOccupiedColumn(ws As Worksheet) As Long
    Dim f As Range
    Set f = ws.Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)
    If Not f Is Nothing Then LastOccupiedColumn = f.Column
End Function
Function LastOccupiedRow(ws As Worksheet) As Long
    Dim f As Range
    Set f = ws.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
    If Not f Is Nothing Then LastOccupiedRow = f.row
End Function

Combine Worksheets With Different Headers

www.un.org/Depts/DGACM/index_spanish.htm 职衔

Option Explicit

Public DataRange As Range
Public Headers As Variant
Public RowsCount As Long
Public ColumnsCount As Long

Option Explicit

Sub CombineWorksheets()

    Const SRC_FIRST_CELL As String = "A1"   fixed (due to  CurrentRegion )
    Const DST_SHEET_NAME As String = "CombinedData"
    Const DST_FIRST_CELL As String = "A1"
    
    Application.ScreenUpdating = False
    
    Dim wb As Workbook: Set wb = ThisWorkbook   workbook containing this code
    
    Dim dsh As Object:
    
    On Error Resume Next
        Set dsh = wb.Sheets(DST_SHEET_NAME)
    On Error GoTo 0
    
    If Not dsh Is Nothing Then
        Application.DisplayAlerts = False
           dsh.Delete
        Application.DisplayAlerts = True
    End If
   
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare
    
    Dim coll As Collection: Set coll = New Collection
    
    Dim swsp As cWorksheetProperties, sws As Worksheet
    Dim Headers() As Variant, Header As Variant
    Dim sc As Long, dc As Long

    For Each sws In wb.Worksheets
        Set swsp = New cWorksheetProperties
        With sws.Range(SRC_FIRST_CELL).CurrentRegion
            Headers = .Rows(1).Value
            swsp.RowsCount = .Rows.Count - 1
            swsp.ColumnsCount = .Columns.Count
            Set swsp.DataRange = .Resize(swsp.RowsCount).Offset(1)
        End With
        For sc = 1 To swsp.ColumnsCount
            Header = Headers(1, sc)
            If Not dict.Exists(Header) Then
                dc = dc + 1
                dict(Header) = dc
                Headers(1, sc) = dc
            Else
                Headers(1, sc) = dict(Header)
            End If
        Next sc
        swsp.Headers = Headers
        coll.Add swsp
    Next sws
    
    Dim dws As Worksheet: Set dws = wb.Sheets.Add
    dws.Name = DST_SHEET_NAME
    
    Dim drrg As Range: Set drrg = dws.Range(DST_FIRST_CELL).Resize(, dict.Count)
    drrg.Value = dict.Keys
    Set dict = Nothing
    Set drrg = drrg.Offset(1)
    
    Dim drg As Range
    
    For Each swsp In coll
        With swsp
            Set drg = drrg.Resize(.RowsCount)
            For sc = 1 To .ColumnsCount
                drg.Columns(.Headers(1, sc)).Value _
                    = .DataRange.Columns(sc).Value
            Next sc
            Set drrg = drrg.Offset(.RowsCount)
        End With
    Next swsp
    
    Application.ScreenUpdating = True
    
    MsgBox "Worksheets combined.", vbInformation
 
End Sub




相关问题
import of excel in SQL imports NULL lines

I have a stored procedure that imports differently formatted workbooks into a database table, does work on them then drops the table. Here is the populating query. SELECT IDENTITY(INT,1,1) AS ID ...

Connecting to Oracle 10g with ODBC from Excel VBA

The following code works. the connection opens fine but recordset.recordCount always returns -1 when there is data in the table. ANd If I try to call any methods/properties on recordset it crashes ...

Excel date to Unix timestamp

Does anyone know how to convert an Excel date to a correct Unix timestamp?

C# GemBox Excel Import Error

I am trying to import an excel file into a data table using GemBox and I keep getting this error: Invalid data value when extracting to DataTable at SourceRowIndex: 1, and SourceColumnIndex: 1. As ...

Importing from excel "applications" using SSIS

I am looking for any tips or resources on importing from excel into a SQL database, but specifically when the information is NOT in column and row format. I am currently doing some pre-development ...

热门标签