我有3个打开的Excel文件,我已使用此代码打开;
Dim myWorkbooks As New Collection
Sub GetFile()
Dim fNameAndPath As Variant, i As Long, x As Variant
fNameAndPath = Application.GetOpenFilename("All Files (*.*), *.*", , "Select Files To Be Opened", , True)
If Not IsArray(fNameAndPath) Then
If fNameAndPath = False Then Exit Sub Else fNameAndPath = Array (fNameAndPath)
End If
For i = LBound(fNameAndPath) To UBound(fNameAndPath)
Set x = Workbooks.Open(fNameAndPath(i))
myWorkbooks.Add x
Next
End Sub
我在一本工作簿中合并了我需要的所有表格。有一个名为" KomKo"在本工作手册中。我还有其他表格,其中包括数据(2)和#34; ,"数据(3)"和"数据(4)"。这些表格可能超过4张所以我可能会将表格称为"数据(11)"等等。我希望能够复制所有"数据"的C列。将其粘贴并粘贴到" KomKo"的A列;片。我应该能够将这些值粘贴到该列A的下一个空值。
我该怎么做?
答案 0 :(得分:1)
因此,在您更正了问题后,此代码应该执行所需的工作:
Dim masterSheet As Worksheet
Set masterSheet = Sheets("Komko")
'Variable to save the used Range of the master sheet
Dim usedRangeMaster As Integer
Dim ws As Worksheet
'loop through each worksheet in current workbook
For Each ws In Worksheets
'If sheetname contains "data" (UCase casts the Name to upper case letters)
If InStr(1, UCase(ws.Name), "DATA", vbTextCompare) > 0 Then
'calculate the used range of the master sheet
usedRangeMaster = masterSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row + 1
'Variable to save the used Range of the sub sheet
Dim usedRangeSub As Integer
'calculate the used range of the sub sheet
usedRangeSub = ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row
'copy relevant range from the subsheet
ws.Range("C1:C" & usedRangeSub).Copy
'paste the copied range after the used range in column a
masterSheet.Range("A" & usedRangeMaster).PasteSpecial
End If
Next ws
答案 1 :(得分:0)
由于您已经拥有一个包含相关工作簿的集合,因此您可以循环使用这些工作簿并将相关内容复制到主wb中。
所以为主表定义一个变量(以便能够引用它) 并且循环内部有一个变量,用于保存“子表”:
Dim mastersheet As Workbook
Set mastersheet = ThisWorkbook 'Assuming the code is inside the master sheet
Dim wb As Workbook
For Each wb In myWorkbooks
'Copy stuff
'Example to get a value from the "subsheet"
mastersheet.Sheets("sheet1").Cells(1, 1).Value = wb.Sheets("sheet1").Cells(1, 1)
Next wb
然后在循环内部复制列c,并将其粘贴到主表的列a中:
wb.Sheets("sheet1").Range("C1").EntireColumn.Copy
mastersheet.Sheets("sheet1").Range("A1").PasteSpecial