Comportament neașteptat de "Pentru Fiecare wks În ActiveWindow.SelectedSheets", aceasta afectează mai mult coloană care ar trebui să fie

0

Problema

am făcut acest cod care funcționează destul de bine, afară de ultima parte:

Comportamentul din ultima parte ar trebui să fie ".Interior.Culoare" și ".Valoarea" a afectat până în ultima populate coloană, în loc să-l afectează în prima celulă de multe alte coloane. Orice idei?

  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

Cel mai bun răspuns

0

Dacă am înțeles ce ai de gând să faci, la urma face ceea ce vrei.

  • Codul ar putea fi abordată în mod diferit (și, eventual, a făcut mai eficient), dacă contextul mai larg a fost cunoscut
  • Cu toate acestea, simt ca asta este doar o etapă în dezvoltarea ta, așa că au rămas cu abordarea ta (ori de câte ori rezonabil).
' 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

Nota 1: Nu sunt sigur de motiv, dar codul introduce 'comparație coloane după fiecare coloană, cu excepția ultima coloană (din datele copiate). Dacă am înțeles intenția dumneavoastră în mod corect, presupun că vrei să faci asta pentru ultima coloană, de asemenea,. Dacă asta e adevărat:

'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

Nota 2: codul Meu modificări scrie <cell value> & " - Comparison" pentru toate celulele de pe fiecare coloană, până la ultimul non-celulă necompletată în fiecare 'comparativ' coloana (inclusiv celule goale de mai sus asta). Dacă vrei să faci asta scrie pentru toate rândurile din datele copiate gama (dacă celulele sunt goale sau nu) ai putea simplifica codul prin plasarea următoarele:

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

Și elimina acest lucru:

    ' 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

Alte Nota / Indicatori:

  1. Recomand Option Explicit în partea de sus a toate modulele (doar salvează o mulțime de depanare din cauza typos)
  2. Nu e nevoie (și nu e bună practică) să declare Public variabilele care sunt utilizate numai la nivel local într-un anumit Sub sau Function. În schimb, declara același lucru la nivel local (de obicei în partea de sus a Sub sau Function).
  3. Este o bună practică de a utiliza caractere de conducere nume de variabile pentru a identifica tipul de date. Poate fi orice lungime, dar este de obicei de 1, 2 sau 3 caractere (coder de preferință). exemplu de mai Sus am folosit lg la ID-ul lung tipuri de date. În mod similar, eu folosesc in pentru Integer, st pentru String, rg pentru Range, etc.
2021-11-24 07:52:25

Nu sunt sigur cât de utilizate pe scară largă maghiară notație este în prezent, și nu a fost întotdeauna o dezbatere pe tema dacă a fost sau nu un lucru bun. Adică, acesta poate fi util, doar OMI în detrimentul lizibilitate (și unele concizie care este secundar).
Chris Strickland

Re 3) ceea Ce pledează aici este "sisteme de maghiar", care este discreditată. Pe de altă parte, "Aplicații maghiară" pot fi utile. Un bun citit (nu despre vba, dar încă relevant)
chris neilsen

@Chris Strickland: de Acord nu e pentru și împotriva. În limbile în care tip de date este implicită (versus explicit), am opta pentru scopul de denumire. În limbi (cum ar fi vba) în cazul în care este explicit, am stick cu 'a încercat și dovedit' ca mi se pare o face mai ușoară depanare.
Spinner

În alte limbi

Această pagină este în alte limbi

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