2015-04-01 94 views
0
A.Range(A2 & Lrow).Copy B.Cells(Rows.Count, "A").End(xlUp).Offset(1, 1) 
A.Cells(1,1).Copy B.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) 

這是代碼複製第一個標題及其對應的列計算範圍引用不同的列

Sheet A         Code Output 

    Male Female      Male  Mike   
    Mike Rose       Female John 
    John Kat         Bob 
    Bob  Lisa         Rose 
               Kat 
               Lisa 
          Expected output 

       Male Mike     Male Mike 
         John     Male John 
         Bob    OR  Male Bob 
       Female Rose     Female Rose 
         Kat      Female Kat 
         Lisa     Female Lisa 

讓我解釋一下:當我使用,我用每次進行復制粘貼正常碼,我得到男性和女性連續這是錯誤的,因爲應該從玫瑰。我發現唯一的問題可能是我用來抵消第一列的範圍是通過上升找到的,所以編譯器會在第一行中上升到第二行,而我希望它直到列B中的最後一個值。任何這種輸出可能?

B.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) 

這是我需要改變我認爲但需要幫助。謝謝。

回答

0

你應該能夠修改此使其工作:

male_count = Application.WorksheetFunction.CountA(Worksheets("Sheet A").Range("A1:A100")) 
female_count = Application.WorksheetFunction.CountA(Worksheets("Sheet A").Range("B1:B100")) 

Worksheets("Sheet A").Range("A1").Copy 
Worksheets("code output").Range("A1").PasteSpecial Paste:=xlPasteValues 

Worksheets("Sheet A").Range("A2:A" & male_count).Copy 
Worksheets("code output").Range("B1").PasteSpecial Paste:=xlPasteValues 

Worksheets("Sheet A").Range("B1").Copy 
Worksheets("code output").Range("A" & male_count).PasteSpecial Paste:=xlPasteValues 

Worksheets("Sheet A").Range("B2:B" & female_count).Copy 
Worksheets("code output").Range("B" & male_count).PasteSpecial Paste:=xlPasteValues 
+0

什麼male_count和他們 – Meesha 2015-04-01 20:34:27

+0

分別female_count有男性和女性的條目數,包括頭。 – Economist 2015-04-01 20:37:54

0
Sub Test() 
    Dim wb As Workbook 
    Set wb = ThisWorkbook 
    Dim ws As Worksheet 
    Set ws1 = wb.Sheets("Sheet1") 'Rename Sheet1 to your sheet where source data is 
    Set ws2 = wb.Sheets("Sheet2") 'Rename Sheet2 to your sheet where you want output 
    ws1.Activate 
    LastRow1 = Range("A" & Rows.Count).End(xlUp).Row 'Change Column Letter to where you have Male names 
    LastRow2 = Range("B" & Rows.Count).End(xlUp).Row 'Change Column Letter to where you have Femal names 
    Set MaleRng = ws1.Range(Cells(2, 1), Cells(LastRow1, 1)) 
    Set FemaleRng = ws1.Range(Cells(2, 2), Cells(LastRow2, 2)) 
    i = 1 
    For Each Male In MaleRng 
    ws2.Cells(i, 1) = "Male" 
    ws2.Cells(i, 2) = Male.Value 
    i = i + 1 
    Next 
    ws2.Activate 
    i = ws2.Range("A" & Rows.Count).End(xlUp).Row 
    j = i + 1 
    For Each Female In FemaleRng 
    ws2.Cells(j, 1) = "Female" 
    ws2.Cells(j, 2) = Female.Value 
    j = j + 1 
    Next 

    End Sub 
+0

這應該完美無缺! – 2015-04-02 03:23:24