MS Excel VBA – 循环遍历行和列

你好,stackoverflow社区,

我必须承认我主要是在MS Access中的代码,并且对MS Excel VBA有非常有限的经验。

我目前的目标是这样的,我有一个“费用报告”被发送给我扣除,这个报告有许多列不同的帐户名称可能会填充或可能为空。

我的第一步是从第一条logging开始(第14行; AK列包含有关扣除的个人信息),然后跳到第一个扣除科目(扣除科目开始于列L并跨越列DG),检查每个单元格是否为空如果存在价值,则需要将其复制到从第2行(J栏扣除本身)开始的外部工作簿“工资单模板”中,并将其中的某些个人信息与该扣除有关的“费用报告”中的原始行(currRow:从“费用报告”到“工资模板”栏B,C,D的C,E,F列)。

然后向右移动,直到下一个单元格包含一个值,然后在“工资单模板”中的新行上重复此过程。 一旦最后一列(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>` 

下面的代码可能会做你以后的事情:

 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