2016-07-28 169 views
0

我已经制作了一个由新的换行符(\ n)分隔的ID组成的字符串。现在我想将这个字符串粘贴到excel中,以便所有ID都被粘贴到列中的不同单元格中。对于所有这些,我已经将$ finCode中的字符串填充到剪贴板中。现在我需要在excel表格中选择一个单元格,然后将整个字符串粘贴到该单元格中,以便所有ID都被填充到同一列中excel的所有不同单元格中。 的代码如下:使用PowerShell将剪贴板中的数据粘贴到Excel单元格中

我导入工作簿:

$workbook = $xldoc.Workbooks.Open($testType) 

我检查工作表上下工夫:

$mysheet = $workbook.worksheets | where {$_.name -eq "JPT"} 

,我用这个$ MySheet的工作功能为$ currentSheet

现在功能如下:

addtitle() 
{ 
$finCode="" 

         $fRow=$intRow 


         for($intRow = $fRow ; $intRow -le $maxRow ; $intRow++){ 

          $codeName = $currentCode 
          $fin = $codeName + "_" + $i + "`n" 
          $finCode=$finCode+$fin 


          $i= $i + 1 
         } 

         # 

         $currentSheet.Cells.Item($fRow,$currentCol).Value2 = $finCode 

         $clipboardData = $finCode 

         [System.Windows.Forms.Clipboard]::SetText($ClipboardData) 



         $currentSheet.Cells.Item($fRow,$currentCol).Select() | Out-Null 

         $currentSheet.Paste($finCode) | Out-Null 

} 

我得到这个错误:你不能调用一个空值表达式的方法。 请帮助我在Excel的不同单元格中填充字符串的值。

回答

0

我可以建议复制/粘贴的替代方案吗?

我有一个脚本可以生成一个大的Excel工作簿,而我以前使用复制/粘贴方法,因为逐个单元格编写的过程非常缓慢,但是当我试图在同一时间执行其他任何操作时遇到了问题。如果我同时在任何其他应用程序中使用复制/粘贴,它会弄乱我的输出。

我会推荐使用多维数组以及单元格区域的Value2。

这里是一个普通的例子,你应该能够适应您的需求:

# Open Excel 
$excel = New-Object -ComObject Excel.Application 
# Make Excel visible 
$excel.Visible = $true 
# Open new workbook 
$workbook = $excel.Workbooks.Add() 
# Use first sheet 
$worksheet = $workbook.Worksheets.Item(1) 
# Set a base string for the example 
$baseString = "RowTextExample" 
# Set column number 
$columnNum = 1 
# Set starting row number 
$startRowNum = 1 
# Set ending row number 
$endRowNum = 10 
# Create an empty multi-dimensional array that with the first digit equating to the number of rows and second equating to the number of columns 
$multiArray = New-Object 'object[,]' $endRowNum, 1 
# Since rows start at 1 and an array index starts at 0, set a variable to track the array index that starts at 0 
$arrayIndex = 0 
# Start at first row and go to the end row adding appending the base string with the row number 
for($rowNum = $startRowNum; $rowNum -le $endRowNum ; $rowNum++) 
{ 
    $multiArray[$arrayIndex, 0] = $baseString + "_$rowNum" 
    $arrayIndex++ 
} 
# Set the range where the data will be placed; the size must match the size of the multi-dimensional array 
# Example using A1 format instead of column number: $range = $worksheet.Range("A$($startRowNum):A$endRowNum") 
$range = $worksheet.Range($worksheet.Cells($startRowNum, $columnNum), $worksheet.Cells($endRowNum, $columnNum)) 
# Write the multi-dimensional to the range 
$range.Value2 = $multiArray 
+0

嗨@乔恩我应该在哪里提列没有。在范围中。例如在这里提到它的“A”。现在我有了不需要填充3的列,那么我如何在代码(Range)函数中提到这一点。 –

+0

@ shikher.mishra,好吧我更新了代码,使用列号而不是A1格式引用单元格区域。我留下了A1格式的例子,以防其他人发现它有用。 –