Mat*_* A. 3 excel powershell automation vba excel-2010
我有大约70个excel文件,我想要组合成一个文档.每个文档只有一个表格,并遵循以下格式:
我想从每列的Columns AF中获取信息,并将其与来自同一目录中的所有其他文件的信息组合成一个新文件.
注意:我只想捕获列AF,因为在G列中存在一个Yes,No数据集来管理F列中的下拉列表.
我尝试使用Dugan的答案从复制Excel工作表从一个工作簿到另一个使用Powershell,但它产生了一个文件,其中部分数据分布在两个工作表中.
这是代码:
$file1 = 'C:\Users\Matthew.Andress\Documents\Excel Test\Book1.xlsx' # source's fullpath
$file2 = 'C:\Users\Matthew.Andress\Documents\Excel Test\Book2.xlsx' # destination's fullpath
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file1, $null, $true) # open source, readonly
$wb1 = $xl.workbooks.open($file2) # open target
$sh1_wb1 = $wb1.sheets.item(2) # second sheet in destination workbook
$sheetToCopy = $wb2.sheets.item('Sheet1') # source sheet to copy
$sheetToCopy.copy($sh1_wb1) # copy source sheet to destination workbook
$wb2.close($false) # close source workbook w/o saving
$wb1.close($true) # close and save destination workbook
$xl.quit()
spps -n excel
有什么建议?谢谢.
好的,这是几天后,但你可以感谢周末.看看这个,看看你喜欢它.
#Get a list of files to copy from
$Files = GCI 'C:\Users\Matt\Documents\Excel Test\' | ?{$_.Extension -Match "xlsx?"} | select -ExpandProperty FullName
#Launch Excel, and make it do as its told (supress confirmations)
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $True
$Excel.DisplayAlerts = $False
#Open up a new workbook
$Dest = $Excel.Workbooks.Add()
#Loop through files, opening each, selecting the Used range, and only grabbing the first 6 columns of it. Then find next available row on the destination worksheet and paste the data
ForEach($File in $Files[0..4]){
    $Source = $Excel.Workbooks.Open($File,$true,$true)
    If(($Dest.ActiveSheet.UsedRange.Count -eq 1) -and ([String]::IsNullOrEmpty($Dest.ActiveSheet.Range("A1").Value2))){ #If there is only 1 used cell and it is blank select A1
        [void]$source.ActiveSheet.Range("A1","F$(($Source.ActiveSheet.UsedRange.Rows|Select -Last 1).Row)").Copy()
        [void]$Dest.Activate()
        [void]$Dest.ActiveSheet.Range("A1").Select()
    }Else{ #If there is data go to the next empty row and select Column A
        [void]$source.ActiveSheet.Range("A2","F$(($Source.ActiveSheet.UsedRange.Rows|Select -Last 1).Row)").Copy()
        [void]$Dest.Activate()
        [void]$Dest.ActiveSheet.Range("A$(($Dest.ActiveSheet.UsedRange.Rows|Select -last 1).row+1)").Select()
    }
    [void]$Dest.ActiveSheet.Paste()
    $Source.Close()
}
$Dest.SaveAs("C:\Users\Matt\Documents\Excel Test\Book1.xlsx",51)
$Dest.close()
$Excel.Quit()
这将得到一个excel文件列表,打开Excel并创建一个新文档,然后遍历文件列表,打开它们,选择列AF,复制这些列,返回到新工作簿并选择下一个可用行,并粘贴其他工作簿中的数据.然后它关闭该文件并继续下一个文件.最后,它会保存您的工作簿中的所有数据并关闭excel.
| 归档时间: | 
 | 
| 查看次数: | 11659 次 | 
| 最近记录: |