Добавление столбца с указанием источника данных на листе - PullRequest
0 голосов
/ 20 июня 2019

Основная функция программы состоит в том, чтобы скопировать все данные в открытых листах и ​​поместить их в лист с именем «объединенный». Все работает хорошо, однако я хочу добавить столбец под названием «Источник данных», в котором можно указать, откуда поступили данные (например, Sheet1, Sheet2). Но дело в том, что выводится неверное имя листа.

Я пробовал разные коды и приложил то, что в настоящее время работает ниже. Я выделю ту часть, в которой, как я полагаю, возникла проблема. Я был бы очень признателен за помощь, так как я сам не кодер (только что узнал об этом неделю назад).

  For Each wksSrc In ThisWorkbook.Worksheets

       'Skip Destination worksheet
        If wksSrc.Name <> wksDst.Name And wksSrc.Name <> "Tool" Then
            With wksSrc

                'Identify the last row and column on this sheet
                'so we know when to stop looping through the data
                lngLastSrcRowNum = LastOccupiedRowNum(wksSrc)
                lngLastSrcColNum = LastOccupiedColNum(wksSrc)

                'Identify the last row of the Destination sheet
                'so we know where to (eventually) paste the data
                lngLastDstRowNum = LastOccupiedRowNum(wksDst)

                'Loop through the headers on this sheet, looking up
                'the appropriate Destination column from the Final
                'Headers dictionary and creating ranges on the fly

                For lngIdx = 1 To lngLastSrcColNum

                    strColHeader = Trim(CStr(.Cells(1, lngIdx)))

                    'Set the Destination target range using the
                    'looked up value from the Final Headers dictionary
                    Set rngDst = wksDst.Cells(lngLastDstRowNum + 1, _
                                              dicFinalHeaders(strColHeader))

                    'Set the source target range using the current
                    'column number and the last-occupied row
                    Set rngSrc = .Range(.Cells(2, lngIdx), _
                                        .Cells(lngLastSrcRowNum, lngIdx))

                    'Copy the data from this sheet to the destination
                    rngSrc.Copy Destination:=rngDst

                Next lngIdx

                Dim TargetColumn As Long
                Dim FinalRow As Long
                Dim rngAddress As Range
                Dim i As Long


                With wksDst
                    FinalRow = .Cells(.Rows.Count, "A").End(xlUp).Row
                    Set rngAddress = .Range("A:Z").Find("Data Source")

                     If Not rngAddress Is Nothing Then
                        TargetColumn = rngAddress.Column 

           ''''THIS IS THE PART WHERE I ASSUME THE PROBLEM COMES FROM'''''
                            For i = 1 To FinalRow
                            .Cells(i, TargetColumn).Value = wksSrc.Name
                            Next i

                     End If

                 End With

            End With
        End If

    Next wksSrc

End Sub

Я уже добавил столбец «Источник данных», но часть wksSrc.Name в коде всегда выводит только имя последнего рабочего листа, когда оно должно быть другим / динамическим, в зависимости от рабочих листов, откуда я получил данные.

Это может помочь. Когда я устанавливаю значение i в 1, он выводит правильное имя листа, однако он заменяет заголовок столбца именем листа, и цикл выполняется только один раз. Когда я делаю значение i равным 2, оно выводит неправильное имя листа, но начинает выводить в правильной первой пустой строке столбца источника данных.

1 Ответ

0 голосов
/ 20 июня 2019

Как уже упоминалось в комментариях.Вы перебираете столбец ВЕСЬ имя источника каждый раз.Таким образом, в конце вашего процесса у вас останется последний зацикленный лист.Таким образом, чтобы преодолеть это, вам нужно StartRow, а также FinalRow только для циклического прохождения данных с этого листа.См. Код ниже (не проверено), но я думаю, что вы получите представление о том, как реализовать, и это может сработать.

For Each wksSrc In ThisWorkbook.Worksheets

       'Skip Destination worksheet
        If wksSrc.Name <> wksDst.Name And wksSrc.Name <> "Tool" Then
            With wksSrc

                'Identify the last row and column on this sheet
                'so we know when to stop looping through the data
                lngLastSrcRowNum = LastOccupiedRowNum(wksSrc)
                lngLastSrcColNum = LastOccupiedColNum(wksSrc)

                'Identify the last row of the Destination sheet
                'so we know where to (eventually) paste the data
                lngLastDstRowNum = LastOccupiedRowNum(wksDst)

                'Loop through the headers on this sheet, looking up
                'the appropriate Destination column from the Final
                'Headers dictionary and creating ranges on the fly

                For lngIdx = 1 To lngLastSrcColNum

                    strColHeader = Trim(CStr(.Cells(1, lngIdx)))

                    'Set the Destination target range using the
                    'looked up value from the Final Headers dictionary
                    Set rngDst = wksDst.Cells(lngLastDstRowNum + 1, _
                                              dicFinalHeaders(strColHeader))

                    'Set the source target range using the current
                    'column number and the last-occupied row
                    Set rngSrc = .Range(.Cells(2, lngIdx), _
                                        .Cells(lngLastSrcRowNum, lngIdx))

                    'Copy the data from this sheet to the destination
                    rngSrc.Copy Destination:=rngDst

                Next lngIdx

                Dim TargetColumn As Long
                Dim FinalRow As Long, StartRow As Long
                Dim rngAddress As Range
                Dim i As Long


                With wksDst

                    Set rngAddress = .Range("A:Z").Find("Data Source")

                     If Not rngAddress Is Nothing Then
                        TargetColumn = rngAddress.Column
                        'set the start for this sheet
                        StartRow = lngLastDstRowNum + 1
                        'set the final row for this worksheet
                        FinalRow = .Cells(.Rows.Count, "A").End(xlUp).Row

                        .Range(.Cells(StartRow, TargetColumn), .Cells(FinalRow, TargetColumn)).Value = wksSrc.Name
                     End If

                 End With

            End With
        End If

    Next wksSrc

Как видно, настройка диапазона на wksDst должна занятьво внимание данные листов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...