How to Paste Data in Columns and Rows in this way

前端 未结 1 1872
后悔当初
后悔当初 2021-01-27 09:08

i have some label data to print in columns and rows format based on the user defined input Value. their are 3 main inputs based conditions:

1) No of starting label to sk

相关标签:
1条回答
  • 2021-01-27 09:55

    Looking at your code, my first thought was it could be simplified. Once I did this, I began modifying to add needed requirements. The main task was keeping track of the current location. The code ended up like this:

    Option Explicit
    
    Public Sub GenerateLabels(ByVal LabelsToSkip As Integer, ByVal LabelsPerRow As Integer, ByVal RowsPerPage As Integer)
       Dim shdata As Worksheet
       Dim shgenerate As Worksheet
       Dim shDesignFormat As Worksheet
       Dim curRow As Long
       Dim curCol As Long
       Dim RowsPerPageCount As Long
       Dim r As Long
       Dim r2 As Long
    
       Set shdata = ThisWorkbook.Sheets("Database")
       Set shgenerate = ThisWorkbook.Sheets("LabelGenerate")
       Set shDesignFormat = ThisWorkbook.Sheets("LabelDesignFormatBeforePrint")
    
       shgenerate.UsedRange.ClearContents
    
       curRow = 1
       curCol = 1
       RowsPerPageCount = 1
    
       For r = 2 To shdata.Range("A" & Rows.Count).End(xlUp).Row
          '======== Copy From Data Sheet============
          shdata.Cells(r, "A").Copy
          shDesignFormat.Range("B3").PasteSpecial  'pasting data to design sheet before print (to format data)
    
          For r2 = 1 To shdata.Cells(r, "B").Value + LabelsToSkip
             '=====Paste to Generate Sheet ====
             If curCol > LabelsPerRow * 2 Then  '* 2 for double spacing
                curCol = 1
    
                If RowsPerPage > 0 And (RowsPerPageCount + 1) Mod (RowsPerPage + 1) = 0 Then
                   curRow = curRow + 10  'new page
                   RowsPerPageCount = 1
                Else
                   curRow = curRow + 2
                   RowsPerPageCount = RowsPerPageCount + 1
                End If
             End If
    
             If r2 > LabelsToSkip Then
                LabelsToSkip = 0
                shDesignFormat.Range("B3").Copy Destination:=shgenerate.Cells(curRow, curCol)
             End If
    
             curCol = curCol + 2
          Next r2
       Next r
    
       Application.CutCopyMode = False
    End Sub
    

    I recommend using Option Explicit and declaring all variables that you need.

    0 讨论(0)
提交回复
热议问题