2017-04-24 41 views
0

如果列B中存在值,則需要一個宏來寫入列A中存在的行值。Excel宏 - 基於來自其他列的值獲取一列的值

例如:

Column A Column B 
Arjun 
Arun   12 

對於上面的例子,我需要一個宏可以在工作簿與頭「名稱」的Sheet2中寫「阿倫12」和「時間」。之前這個宏應完全清除Sheet 2中存在的數據。

+1

你到目前爲止嘗試過什麼?分享你的代碼嘗試,我們很樂意幫你 –

回答

0

這應該完成你所追求的。

Sub DoStuff() 

Dim lastRow As integer, lastRowSheet2 As integer, i As Integer 
Dim sheet1 As WorkSheet, sheet2 As Worksheet 

Set sheet1 = Sheets("Sheet1") 
Set sheet2 = Sheets("Sheet2") 

lastRow = sheet1.Range("A" & Rows.Count).End(xlUp).Row 

sheet2.Cells.Clear 

For i = 1 To lastRow 

If sheet1.Range("A" & i).Value <> "" And sheet1.Range("B" & i).Value <> "" then 

    lastRowSheet2 = sheet2.Range("A" & Rows.Count).End(xlUp).Row 

    sheet1.Range("A" & i & ":B" & i).Copy Destination:= sheet2.Range("A" & lastRowSheet2 + 1) 

End If 

Next i 

End Sub 
+0

'lastRow','lastRowSheet2'和'i'應該是'Long'類型。 Excel比'Integer'可以處理更多的行。 –

+0

爲了安全和完整性,或許是 – Skaterhaz

+0

不僅可能,它應該是'長'。因爲它在'Integer'之上的行計數肯定會*崩潰,這不僅是「很好有功能」的嚴重問題。不使用'長'來進行行計數是非常糟糕的做法。 –

1

如果B不是空字符串,這將複製A列和B列的所有行從Sheet1複製到Sheet2。還將添加標題「名稱」和「小時」。

Option Explicit 'requires that every variable has to be defined before use, e.g. with a Dim statement. 

Sub DoStuff_GoodPractice() 
    Dim lastRowSrc As Long, lastRowDest As Long, i As Long 'declare row counts as Long so all rows can be used 
    Dim shtSource As Worksheet, shtDestination As Worksheet 

    Set shtSource = ThisWorkbook.Worksheets("Sheet1") 'full qualified identification of the worksheets 
    Set shtDestination = ThisWorkbook.Sheets("Sheet2") 

    lastRowSrc = shtSource.Range("A" & shtSource.Rows.Count).End(xlUp).Row 'determine the last used row 

    'clear destination sheet and write headers: 
    shtDestination.Cells.Clear 
    shtDestination.Range("A1").Value = "Name" 
    shtDestination.Range("B1").Value = "Hours" 

    lastRowDest = 1 'start with row 1 as destination 

    For i = 1 To lastRowSrc 'loop through all used rows 
     If shtSource.Range("A" & i).Value <> vbNullString And _ 
      shtSource.Range("B" & i).Value <> vbNullString Then 'check if cells are not a null string 
      shtSource.Range("A" & i & ":B" & i).Copy Destination:=shtDestination.Range("A" & lastRowDest + 1) 'copy current row 
      lastRowDest = lastRowDest + 1 'jump to the last used row in destination 
     End If 
    Next i 
End Sub