2016-10-10 79 views
0

你好計算器社區,MS Excel的VBA - 循環通過行和列

我必須承認,我主要是MS Access中的代碼,並有MS Excel的VBA的經驗非常有限。

我目前的目標是這樣的,我有一個「費用報告」通過扣款發送給我,這份報告有很多不同的帳戶名稱列,可能會填充或可能爲空。

我的第一步是從第一條記錄開始(第14行; AK列包含關於扣減的個人信息),然後跳到第一個扣除科目(扣除科目從列L開始並跨越列DG)每個單元格爲空,如果它繼續向右移動,如果存在值,則需要將其複製到從第2行開始的外部工作簿「工資單模板」(列J爲扣除本​​身)以及副本「費用報告」中與原始行相關的一些個人信息(currRow:C列,E,F從「費用報告」到「工資列表模板」列B,C,D)。

然後向右移動,直到下一個單元格包含一個值,然後在「工資單模板」中的新行上重複此過程。一旦最後一列(DG)執行完畢,我想移動到下一行(第15行),並一直重新開始這個過程,直到我的「使用範圍」中的「LastRow」。

我非常感謝任何反饋,解釋或鏈接,可能會指向我的目標。提前感謝您花時間閱讀這篇文章!

當前的代碼狀態:

`< Sub LoadIntoPayrollTemplate() 
Dim rng As Range 
Dim currRow As Integer 
Dim UsedRng As Range 
Dim LastRow As Long 



Set UsedRng = ActiveSheet.UsedRange 
currRow = 14 


Set wb = ActiveWorkbook '"Expense Report" 
Set wb2 = MyFilepath '"Payroll Template" 


'Copied from another procedure, trying to use as reference   
LastRow = rng(rng.Cells.Count).Row 
Range("A14").Select 
Do Until ActiveCell.Row = LastRow + 1 
    If (ActiveCell.Value) <> prev Then 

     currRow = currRow + 1 

    End If 

    ActiveCell.Offset(1, 0).Select 
Loop 

With Worksheets("Collections") 
    lstRow = .Cells(.Rows.Count, 1).End(xlUp).Row 
    Set rng = .Range(.Cells(14, 12), Cells(lstRow, 111)) 
End With 

End Sub>` 

回答

1

下面的代碼可能會做你是什麼後:

Sub LoadIntoPayrollTemplate() 
    Dim currRowIn As Long 
    Dim currColIn As Long 
    Dim currRowOut As Long 
    Dim wb As Workbook 
    Dim wb2 As Workbook 

    Set wb = ActiveWorkbook '"Expense Report" 
    Set wb2 = Workbooks.Open(Filename:=MyFilepath & "\" & "Payroll Template.xlsx") 
    'or perhaps 
    'Set wb2 = Workbooks.Open(Filename:=wb.path & "\" & "Payroll Template.xlsx") 

    With wb.ActiveSheet 
     currRowOut = 1 
     For currRowIn = 14 To .UsedRange.Row + .UsedRange.Rows.Count - 1 
      For currColIn = 12 To 111 
       If Not IsEmpty(.Cells(currRowIn, currColIn)) Then 
        currRowOut = currRowOut + 1 
        'I'm not sure which worksheet you want to write the output to 
        'so I have just written it to the first one in Payroll Template 
        wb2.Worksheets(1).Cells(currRowOut, "J").Value = .Cells(currRowIn, currColIn).Value 
        wb2.Worksheets(1).Cells(currRowOut, "B").Value = .Cells(currRowIn, "C").Value 
        wb2.Worksheets(1).Cells(currRowOut, "C").Value = .Cells(currRowIn, "E").Value 
        wb2.Worksheets(1).Cells(currRowOut, "D").Value = .Cells(currRowIn, "F").Value 

       End If 
      Next 
     Next 
    End With 

    'Save updated Payroll Template 
    wb2.Save 

End Sub 
+0

完美地工作!非常感謝 – Ace16150s