예기치 못한 작동의"각 wks 에 ActiveWindow.SelectedSheets",그것은 더 많은 영향을 미치는 열야

0

질문

나는 이 코드는 꽤 잘 작동의 마지막 부분:

의 행동을 마지막 부분야는".인테리어입니다.색"및".값이"영향을 받는 마지막까지 채워 컬럼,대신에 영향을 미치는 첫 번째 셀의 다른 많은 열이 있습니다. 어떤 아이디어가?

  Sub Sample_Workbook()
        
        'Creation of new workbook
        Application.ScreenUpdating = False        
        Workbooks.Add
        
        Set wb = ActiveWorkbook
        wb.SaveAs ThisWorkbook.Path & "etc.xlsx"
        
        'following variable is declared for sending mail purpose
        SourceWorkbook = ActiveWorkbook.Name
        
        Set this = Workbooks("Sample")
        Set wb = ActiveWorkbook
        Set ws1 = wb.Sheets("Sheet1")
        wb.Sheets.Add After:=Sheets(1)
        Set ws2 = wb.Sheets(2)
        wb.Sheets.Add After:=Sheets(2)
        Set ws3 = wb.Sheets(3)
        ws1.Name = "Sheet1"
        ws2.Name = "Sheet2"
        ws3.Name = "Sheet3"
        
        
        'Model the new excel with the requirements:
        Dim Population, Population2 As Range
        Dim lastRow As Long, firstRow As Long
        Dim sampleSize As Long
        Dim unique As Boolean
        Dim i As Long, d As Long, n As Long
        
        
        'following function perfoms all the calculations and copy and pasting        
            
            doTheJob x, y, z, num, q           
            doTheJob x, y, z, num, q 
            doTheJob x, y, z, num, q 
                
        'copy and paste the remaining sheets from the sample files
            Workbooks.Open ThisWorkbook.Path & "Sample2.xlsx"
                Sheets("Sheetx").Copy After:= _
                 Workbooks(SourceWorkbook).Sheets(6)
            Workbooks("Sample2.xlsx").Close SaveChanges:=False
        
        Application.ScreenUpdating = True
        Application.CutCopyMode = False
        ws1.Select
        wb.Close SaveChanges:=True
        End Sub

'these will make the variable available to all modules of this macro Workbook
Public SourceWorkbook As String
Public this, wb As Workbook
Public data As Range
Public output As Range
Public ws1, ws2, ws3 As Worksheet
Public LastCol As Long
Public wks As Worksheet
Public iCol As Long




'FUNCTION
Sub doTheJob(x As String, y As String, z As String, num As Integer, q As String)

    'beginning logic.
    this.Worksheets(x).Activate

Set Population = Range("a3", Range("a3").End(xlDown))
    sampleSize = this.Worksheets("SNOW Reports").Range(y).Value

Set r = Population
    lastRow = r.Rows.Count + r.Row - 1
    firstRow = r.Row


    For i = 1 To sampleSize
   Do
   
    unique = True
    n = Application.WorksheetFunction.RandBetween(firstRow, lastRow)
    
        For d = 1 To i - 1
        'wb.Sheets(z).Activate
        
          If wb.Sheets(z).Cells(d + 1, 50) = n Then
            unique = False
            Exit For
            End If
        Next d
        
          If unique = True Then
          Exit Do
          End If
        
    Loop
    
    Set data = this.Worksheets(x).Range("a" & n, Range("a" & n).End(xlToRight))
    Set output = wb.Worksheets(z).Range("A" & i + 1)
     
    output.Resize(data.Rows.Count, data.Columns.Count).Value = data.Value
        'THE NEXT LINE IS JUST FOR DELETEING LAST COLUMN PURPOSE
    wb.Worksheets(z).Cells(1, 50) = "REF COL"
    wb.Worksheets(z).Cells(i + 1, 50) = n
    
 this.Worksheets(x).Activate
    
Next i

    'delete REF COL:
       With wb.Sheets(z)
            .Columns(50).Delete
        End With
    
    'copy and paste header:
    Set data = this.Worksheets(x).Range("a2", Range("a2").End(xlToRight))
    Set output = wb.Sheets(z).Range("A1")
    
    output.Resize(data.Rows.Count, data.Columns.Count).Value = data.Value
     
'_________________________________________________________________________________________________________

'copy and paste into new sheet with recorded macro
    
   wb.Activate
   Sheets.Add(After:=Sheets(num)).Name = q
   wb.Worksheets(z).Cells.Copy Destination:=wb.Worksheets(q).Range("A1")
             
    'create columns and add color and text dinamically
    For Each wks In ActiveWindow.SelectedSheets
        With wks
            For iCol = .Cells.SpecialCells(xlCellTypeLastCell).Column To 2 Step -1
                .Columns(iCol).Insert
                With Cells(1, iCol)
                .Interior.Color = 65535
                .Value = Cells(1, iCol - 1) & " - Comparison"
                End With
            Next iCol
        End With
    Next wks

End Sub
excel foreach vba
2021-11-23 21:01:44
1

최고의 응답

0

내가 이해하는 경우 당신이 무엇을 할 목표로 하는 다음 당신이 원하는 않습니다.

  • 코드가 될 수 있는 다르게 접근한(그리고 아마도 만들어 더 효율적으),경우에는 더 큰 문맥에 알려졌
  • 그러나,나는 감각 이 단계에서의 개발,그래서 머물렀으로 접근 방식(어디서나 적당한).
' I suggest this goes to the top of the sub (no need for public declaration)
' Note the shorthand declaration: 'lgRow&' is the same as `lgRow as Long'
    Dim lgRow&, lgCol&, lgLastRow&
             

' Replaces the code starting with the next comment 
    'create columns and add color and text dynamically
    For Each wks In ActiveWindow.SelectedSheets
        With wks
            For lgCol = .Cells.SpecialCells(xlCellTypeLastCell).Column To 2 Step -1
                
                ' Insert a column (not sure why you're not doing this after the last column also)
                .Columns(lgCol).Insert
                
                ' Get last row with data in the column 1 to the left
                With .Columns(lgCol - 1)
                    lgLastRow = .Cells(.Cells.Count).End(xlUp).Row
                End With
                    
                ' In the inserted column:
                ' o Set cell color
                ' o Set value to corresponding cell to the left, appending ' - Comparison'
                For lgRow = 1 To lgLastRow
                    With .Cells(lgRow, lgCol)
                        .Interior.Color = 65535
                        .Value = .Offset(0, -1) & " - Comparison"
                    End With
                Next lgRow
            Next lgCol
        End With
    Next wks

참고 1:의 확실하지 않다는 이유만 코드에 삽입하는'비교 열 각 후 열을 제외하고,마지막 열(복사된 데이터의). 내가 이해하는 경우 당신의 의도를 제대로 나가고 싶다고 가정해보겠습니다 이를 위해 마지막 열도. 그것이 진실한 경우:

'change this line
    For lgCol = .Cells.SpecialCells(xlCellTypeLastCell).Column To 2 Step -1
'To:
    For lgCol = .Cells.SpecialCells(xlCellTypeLastCell).Column + 1 To 2 Step -1

참고 2:제한 코드 변경을 쓰기 <cell value> & " - Comparison" 모든 세포에서 각각의 열을 마지막 비 빈 세포에서 각각의'에 비해'칼럼(을 포함한 빈 세포에 위). 당신이 원하는 경우에 쓰는 모든 행에 대한 복사 데이터 범위(는지 여부를 세포이 비어 있거나지 않)단순화할 수 있습니 코드를 배치하여 다음과 같다:

' Insert this:
    lgLastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
'above line:
    For lgCol = ....

고 제거하는 이:

    ' Get last row with data in the column 1 to the left
    With .Columns(iCol - 1)
        lgLastRow = .Cells(.Cells.Count).End(xlUp).Row
    End With

다른 참고/포인:

  1. 추천 Option Explicit 의 맨 위에는 모든 모듈(다만 저장 많은 디버깅으로 인해 오타)
  2. 가 필요 없음(그리고 그것의 좋지 않은 연습)을 선언 Public 변수만 사용되는 로컬에서 주어 SubFunction. 대신에,선언 같은 로컬로(에서 일반적으로 최고의 SubFunction).
  3. 그것은 좋은 연습하는 사용자의 변수 이름에는 데이터를 입력합니다. 의 길이가 될 수 있습,그러나 일반적으로 1,2 또는 3 문자(코더 설정). 예를 들어 위의 내용 lg ID 긴 데이터 유형이 있습니다. 마찬가지로,사용 inInteger, stString, rgRange니다,등등.
2021-11-24 07:52:25

나는 확실하지 않는 방법에 널리 이용되어 현재,그리고 항상 있었는지에 대한 토론이나 그것은 좋은 일입니다. 난 것이 유용할 수 있습니다,그냥 IMO 의 비용으로 가독성이(그리고 몇 가지 간결하는 보조).
Chris Strickland

재 3)무엇을 옹호하고 여기에"시스템"헝가리어가 널리 불신. 한편,"애플 리케이션"헝가리어 유용할 수 있습니다. 좋은 읽기 (지에 대해 vba,하지만 여전히 관련)
chris neilsen

@크리스 랜드:동의 없고 한다. 언어에서는 데이터 형식이 암시적(대 명시적),선택 목적을 위해 지명하고 있다. 에서 이용하는 언어(예:vba)의 명시적,내가 지팡이와 함께'시도하고 검증 된'나는 그것을 찾을 디버깅을 더 쉽게.
Spinner

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................