【问题标题】:To get the value of last cell used in Excel获取 Excel 中使用的最后一个单元格的值
【发布时间】:2020-03-13 23:31:09
【问题描述】:
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
$WorkBook = $objExcel.Workbooks.Open($filepath)
$WorkBook.Sheets | Select-Object -Property Name
$WorkSheet = $WorkBook.Sheets.Item($sheetname)
$worksheetrange = $WorkSheet.UsedRange
$last = $worksheetrange.Rows.Count

我已经使用了 3 行并得到答案 3,这是正确的,我想获得第 3 行中存在的值,并且当我们继续添加行时,如何追加?

【问题讨论】:

  • 我不清楚你的问题是什么。你想达到什么目的?什么没有按预期工作?
  • 我想从我粘贴的图像中读取值“17/11/2017”,即 A 列中的最后一行。

标签: excel powershell vba


【解决方案1】:

如果你想坚持使用 powershell。试试这个。。

$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $False
$WorkBook = $objExcel.Workbooks.Open($filepath)
$WorkSheet = $objExcel.WorkSheets.item($sheetname)
$WorkSheet.activate()

[int]$lastRowvalue = ($WorkSheet.UsedRange.rows.count + 1) - 1
$lastrow = $WorkSheet.Cells.Item($lastRowvalue, 1).Value2
write-host $lastrow

$objExcel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel) | out-null

我假设您已经指定了 $filepath$sheetname。每次运行后不要忘记关闭 Excel。

【讨论】:

    【解决方案2】:

    这样就可以了,只需将 Sheet1 更改为您的实际工作表:

    LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row 
    'This will find the last used row on column A of Sheet1
    
    value = Sheet1.cells(LastRow,1).value 
    'Place the value of that cell into a variable
    
    Msgbox value 
    'Display the variable to the user in a msgbox
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    • 我唯一担心的是这段代码sn-p是VB(宏,Visual Basic),但原来的问题是找PowerShell的例子。
    【解决方案3】:

    Shanayl 提供的方法确实可以正常工作,但请记住,它使用不计算空白的计数方法。下面是一个:

    $filepath = "F:\Drives.xlsx"
    $xl=New-Object -ComObject "Excel.Application"  
    $wb=$xl.Workbooks.open($filepath)
    $ws=$wb.ActiveSheet 
    $cells=$ws.Cells
    
    $Lastrowno =$Ws.UsedRange.SpecialCells(11).row
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多