计算范围引用不同的列

时间:2015-04-01 20:12:10

标签: excel vba excel-vba

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

让我解释一下:当我使用我每次使用的普通代码进行复制粘贴时,我在连续行中得到男性和女性,这是错误的女性应该从 Rose 开始。我看到唯一的问题可能是我用来偏移第一列的范围是通过上升找到的,因此编译器将首先上升到第2行,而我希望它直到列B中的最后一个值。任何这种输出可能吗?

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

这是我需要改变的想法,但我需要帮助。感谢。

2 个答案:

答案 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

答案 1 :(得分: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