简体   繁体   English

VBA-Excel公式计算

[英]VBA - Excel Formula Caclulation

I want to write a code in vba were produce a simple calculation, activesheet.cells(i,3) = activesheet.cells(i,2) * activesheet.cells(i,1) 我想在VBA中编写代码以进行简单的计算,activesheet.cells(i,3)= activesheet.cells(i,2)* activesheet.cells(i,1)

My question here is when i run once the code and then change the values on cells(i,2) and cells(i,1), i want the the cells(i,3)cell to automatically calculate the new value 我的问题是,当我运行一次代码,然后更改cells(i,2)和cells(i,1)上的值时,我希望cells(i,3)cell自动计算新值

For example if cells(i,2) = 3 and cells(i,1) = 2 then cells(i,3) = 6 I want to change the manually the values in excel to cells(i,2) = 4, cells(i,1) = 4, without running again the code I want automatically the cells(i,3) = 16 例如,如果cells(i,2)= 3并且cells(i,1)= 2,那么cells(i,3)= 6我想手动将excel中的值更改为cells(i,2)= 4,cells (i,1)= 4,无需再次运行代码,我便自动希望cell(i,3)= 16

This code be in a for loop 这段代码在for循环中

尝试制作一个包含地址的字符串,像这样

activesheet.cells(i,3) = "=" & activesheet.cells(i,2).Address(0, 0) & "*" &  activesheet.cells(i,1).Address(0, 0)

What you need is Macro Event. 您需要的是宏事件。

Right click on the sheet you want to work with and select view code. 右键单击要使用的工作表,然后选择查看代码。 Copy an paste this code: 复制粘贴此代码:

Private Sub Worksheet_Change(ByVal Target As Range)
 On Error GoTo errorHandler
 Application.EnableEvents = True
 Dim lastrow As Long, rango As Range, Hoja As Worksheet
  Set Hoja = ActiveSheet
  lastrow = Application.CountA(Hoja.Range("A:A"))
  Set rango = Hoja.Range("A1:C" & lastrow)
  rango(lastrow, 3).Value = rango(lastrow, 1).Value * rango(lastrow, 2).Value
errorHandler:
End Sub

在此处输入图片说明

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM