【发布时间】:2016-06-06 19:09:18
【问题描述】:
我通过在公式中指定单元格并将它们添加到新工作簿中的指定单元格/列中,将多个工作簿中的单元格添加到单个工作簿中。我还想在我的“if..then..With”语句中包含一个 for 循环。我希望我的“for”循环将指定范围 A2:C57 从每个工作表 3、4、5、6、7、8、9 添加到单元格 G、H、I 等中。如何在我当前的 VBA 代码中添加这个循环?
Sub GetData()
Dim MyPath As String
Dim FileName As String
Dim SheetName As String
Dim n As Long
Dim NewRow As Long
MyPath = "C:\attach"
SheetName = "Title"
FileName = Dir(MyPath & "\*.xlsx")
Do While FileName <> ""
If FileName <> ThisWorkbook.Name Then
With ThisWorkbook.Sheets("Sheet1")
NewRow = .Cells(Rows.Count, 1).End(xlUp).Row + 1
'Transferring cells from worksheet(2)"Title" into "Sheet1" in thisworkbook"
With .Range("A" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B4"
.Value = .Value
End With
With .Range("B" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B5"
.Value = .Value
End With
With .Range("C" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B6"
.Value = .Value
End With
With .Range("D" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B7"
.Value = .Value
End With
With .Range("E" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!A1"
.Value = .Value
End With
With .Range("F" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!A2"
.Value = .Value
End With
'Selects the range A2:C57 from sheets 3,4,5,6,7,8,9
With .Range("G" & NewRow)
Dim i As Integer, j As Integer, k As Integer
k = 1 'row counter for destination sheet
'loop sheets 3-9
For i = 3 To 9
'loop rows 2-57
For j = 2 To 57
'if C is not empty
If WrkBookSrs.Sheets(i).Cells(j, 3).Value <> "" Then
'code here to add A:C on this row into this workbook in sheet1 column G.
k = k + 1'increment counter for next row
End If
Next
【问题讨论】: