用VB读取excel中的A列和B列,并相乘求和
时间: 2024-05-11 19:14:10 浏览: 210
VB读取EXCEL数据
5星 · 资源好评率100%
以下是用VB读取excel中的A列和B列,并相乘求和的示例代码:
```
'引用Microsoft Excel Object Library
Sub MultiplyAndSum()
Dim objExcel As New Excel.Application
Dim objWorkbook As Excel.Workbook
Dim objWorksheet As Excel.Worksheet
Dim lastRow As Long
Dim i As Long
Dim sum As Double
'打开Excel文件
Set objWorkbook = objExcel.Workbooks.Open("C:\example.xlsx")
Set objWorksheet = objWorkbook.Sheets(1)
'获取A列和B列的最后一行
lastRow = objWorksheet.Cells(objWorksheet.Rows.Count, "A").End(xlUp).Row
'循环计算A列和B列的乘积并求和
For i = 1 To lastRow
sum = sum + objWorksheet.Cells(i, "A").Value * objWorksheet.Cells(i, "B").Value
Next i
'关闭Excel文件
objWorkbook.Close SaveChanges:=False
objExcel.Quit
'输出结果
MsgBox "A列和B列的乘积之和为:" & sum
End Sub
```
需要注意的是,该代码需要在引用Microsoft Excel Object Library的情况下才能运行。同时,需要将文件路径修改为实际的文件路径。
阅读全文