简体   繁体   English

Excel使用VBA替换单元格格式

[英]Excel Replacing Cell formatting with VBA

OK so i would like to figure out a way to change the cells within the worksheet behind the scenes of Excel 2007 with VBA so if i have something in Cell A1 and B1 then C1 will automatically populate a answer without having any formulas in the box. 好的,所以我想找到一种方法来改变Excel 2007后面的工作表中的单元格与VBA,所以如果我在单元格A1和B1中有一些东西,那么C1将自动填充答案,而框中没有任何公式。

i tried 我试过了

Private Sub Worksheet_Change()
dim weekCost as integer
dim monthCost as integer
dim salesTax as integer
dim totalCost as integer

weekCost = Range("$A$1")
monthCost = Range("$B$2")

salesTax = (weekCost + monthCost) * .08
totalCost = weekCost + monthCost

totalCost = salesTax + totalCost

totalCost = range("$C$1")

end sub

I cant get the totalcost to stick to that cell any one know how? 我不能让总成本坚持到任何一个人都知道的那个细胞?

您的作业声明是向后的,请尝试:

Range("C1") = totalCost

The most obvious fix is to change the last line to range("$C$1").Value = totalCost . 最明显的解决方法是将最后一行更改为range("$C$1").Value = totalCost

If that doesn't work, here are some other things to consider: 如果这不起作用,可以考虑以下其他一些事项:

  1. One immediate issue I see with the code is that the Worksheet_Change sub should actually be defined as Private Sub Worksheet_Change(ByVal Target As Range) 我在代码中看到的一个直接问题是,Worksheet_Change子实际上应该被定义为Private Sub Worksheet_Change(ByVal Target As Range)

  2. Make sure that the function is in the code page of the specific worksheet where you want the event to be captured . 确保该功能位于您希望捕获事件的特定工作表的代码页中 If you put it into a regular code module it will not be called. 如果将它放入常规代码模块中,则不会调用它。

  3. Another issue you may want to address is that right now the code would recalculate every time that any cell is modified, not just A1 or B1. 您可能想要解决的另一个问题是,现在每次修改任何单元格时,代码都会重新计算,而不仅仅是A1或B1。 You can put the code inside an If statement to limit when the recalculation is performed. 您可以将代码放在If语句中以限制何时执行重新计算。

或工作表(“Sheet1”)。单元格(3,1).Value = totalCost

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

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