2016-01-24 20 views
1

我是VBA的新手。我目前正試圖通過使用宏來找到更快速的方式來複制和粘貼信息。我不知道如何編碼。如何循環訪問兩列並選擇行並添加到行選擇?

我有兩列,我想用For Each循環。 我想遍歷這兩列的每一行並使用If函數。如果第一行在列B(列B單元格<>「」或列B單元格<> 0)中具有值,則選擇該行(即範圍(「A1:B1」))。

循環後,我會複製所選內容並將其粘貼到特定行。 但是,我想繼續添加到該選擇,因爲它循環遍歷每一行,只有當它滿足If條件時,才能在最後複製一次。我如何去結合這一點?

 A   B 
    1 Abc  1 
    2 Def  2 
    3 Geh  3 

回答

0

這是你如何擴展當前的選擇:

Sub macro1() 
Set selectedCells = Cells(1, 2) 
Set selectedCells = Application.Union(selectedCells, Cells(2, 3)) 
selectedCells.Select 
End Sub 

我敢肯定,你可以自己管理自己的代碼的其餘部分,它真的很容易。你已經提到你需要的一切:For Each cell In Range("B1:B5")If聲明

0

請嘗試下面的代碼

Sub test() 
Application.ScreenUpdating = False 
Dim rng As Range, one As Variant 
Dim i As Integer 

'Change the sheet and range name as yours 
'Finding lastrow of destination column 
i = Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row + 1 

' getting input from user 
Set rng = Application.InputBox("Please select a range of cells!", "Please select a range", Selection.Address, , , , , 8) 

    For Each one In rng 
     If one.Value <> "" Or one.Value <> 0 Then 
     Range(one.Offset(0, -1), one).Copy 
     'Change the sheet and range name as yours 
     Sheets("Sheet2").Activate 
     Range("A" & i).Select 
     ActiveSheet.Paste 
     i = i + 1 
     End If 
    Next one 
Application.ScreenUpdating = True 
End Sub 

上面的宏會提示您輸入範圍內進行驗證和複製在列A到Sheet2

以下的代碼驗證和複製粘貼當前選定範圍到Sheet塔A

Sub test() 
Application.ScreenUpdating = False 
Dim rng As Range, one As Variant 
Dim i As Integer 

'Chnage the sheet and range name as yours 
'Finding lastrow of destination column 
i = Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row + 1 

' getting input from user 
Set rng = Selection 

    For Each one In rng 
     If one.Value <> "" Or one.Value <> 0 Then 
     Range(one.Offset(0, -1), one).Copy 
     'Chnage the sheet and range name as yours 
     Sheets("Sheet2").Activate 
     Range("A" & i).Select 
     ActiveSheet.Paste 
     i = i + 1 
     End If 
    Next one 
Application.ScreenUpdating = True 

End Sub 
0

我想你可能會以這種錯誤的方式去做。你是否已經知道你最終想要在哪裏複製所有數據?聽起來像是這樣,因爲你指的是將它複製到「特定行」。如果是這樣,那麼最好使用宏來即時複製Columns A:B中的數據。

因此,舉例來說:

Sub CopyData() 

Const SOURCE_COLUMN1 As Long = 1 ' A 
Const SOURCE_COLUMN2 As Long = 2 ' B 
Const TARGET_COLUMN1 As Long = 5 ' E 
Const TARGET_COLUMN2 As Long = 6 ' F 

Dim lngSourceRow As Long 
Dim lngTargetRow As Long 

    With ThisWorkbook.Sheets("Sheet1") 
    lngSourceRow = 1 
    lngTargetRow = 0 ' Change this to the row above the one you want to copy to; 
    Do While .Cells(lngSourceRow, SOURCE_COLUMN1) <> "" 
     If .Cells(lngSourceRow, SOURCE_COLUMN2) <> "" Then 
     lngTargetRow = lngTargetRow + 1 
     .Cells(lngTargetRow, TARGET_COLUMN1) = .Cells(lngSourceRow, SOURCE_COLUMN1) 
     .Cells(lngTargetRow, TARGET_COLUMN2) = .Cells(lngSourceRow, SOURCE_COLUMN2) 
     End If 
     lngSourceRow = lngSourceRow + 1 
    Loop 
    End With 

End Sub