【问题标题】:Loop and set value for coulmns循环并设置列的值
【发布时间】:2016-10-09 04:13:02
【问题描述】:

我目前正在使用设置值方法从多个工作簿中复制数据。我目前可以遍历所有工作簿并从一张工作表 worksheet2(Title) 中设置值,如下所示,然后将它们复制到我的目的地“sheet1”上的“thisWorkbook”。如何遍历工作表 3 到 9 并使用相同的设置值方法将范围 A2:C57 复制到列 G、H、I 中?

Sub GetData()
Dim MyPath As String
Dim FileName As String
Dim SheetName As String
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

 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

'Copy the range A2:C57 from workheets (3 to 9) and past into columns G,H,I in thisworkbook from every workbook in folder.
'For sheets 3 to 9 set the value range A2:C57 to G,H,I in thisworkbook. This would be done for every workbook in the folder

End With
End If
FileName = Dir

Loop
ThisWorkbook.Sheets("Sheet1").Columns.AutoFit
End Sub

【问题讨论】:

  • for i=3 to 9 | with thisworkbook.sheets(i)?

标签: vba excel


【解决方案1】:

我不完全确定这是否是您要的,但我认为 range.copy 是您想要的。

要获得整个工作表 3-9,您可以使用

' A2:C57 = Cells (2,1),Cells(57,3)
For Sheetindex= 3 to ThisWorkbook.Worksheets.Count
'Copy Worksheet 3 A2:C57

Set SourceRange = ThisWorkbook.WorkSheets(Sheetindex).Range(Cells(2,1),Cells(57,3)) 

' Paste it in Columns G,H,I starting in Row 1.  


SourceRange.Copy (ThisWorkbook.Worksheets("Sheet1").Cells("G1")) 

Next Sheetindex

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 2017-03-17
    相关资源
    最近更新 更多