简体   繁体   English

我需要帮助修复VBA宏

[英]I need help fixing vba macro

I have a dataset that is made up of a number of rows and columns eg 我有一个由许多行和列组成的数据集,例如

a1 b1
a2 b2
a3 b3
a4 b4
a5 b5

I want to write code that will loop through the cells one column at a time calculating an index like this (a2-a1)/(a2+a1). 我想编写代码,一次计算出一个像这样(a2-a1)/(a2 + a1)的索引的单元格。 I want the result to be saved to sheet2. 我希望将结果保存到sheet2。

I have used this code but I keep getting an error. 我已使用此代码,但始终收到错误消息。 It breaks at where I am trying to save the results to sheet2. 它在我尝试将结果保存到sheet2的地方中断。

I need help to fix this code: 我需要帮助来修复此代码:

Sub Combination()

Dim jCell As Range
Dim kCell As Range
Dim result As Double

Sheet2.Cells.Clear

For Each jCell In ActiveSheet.UsedRange
    For Each kCell In ActiveSheet.UsedRange
        result = (jCell.Value - kCell.Value) / (jCell.Value + kCell.Value)

        Sheet2.Cell("result").Value = Sheet1.Cell("result").Value

    Next kCell
Next jCell

End Sub

Thanks in advance 提前致谢

There are a few things wrong (and I'm assuming this is more for learning VBA than for anything practical - so I'll ignore the non-vba ways to do this). 有几件事是错误的(我认为这更多是为了学习VBA,而不是实际的东西-因此,我将忽略使用非vba的方法来执行此操作)。

One is that I've never seen syntax like this: 一个是我从未见过这样的语法:

Sheet2.Cell("result").Value = Sheet1.Cell("result").Value

Another is that your dataset consists of string type data eg "a1" b1" - now why would you want to do a mathematical operation with strings? Are you trying to combine them(concatenate them)? - otherwise you will just get nonsense numbers if you do arbitrary mathematical operations with strings. 另一个是您的数据集由字符串类型数据组成,例如“ a1” b1”-现在您为什么要对字符串进行数学运算?您是否尝试将它们组合(连接)?-否则,您将得到无意义的数字您可以对字符串进行任意数学运算。

A third is that you need a way to write the output to sheet two in each row. 第三个是您需要一种将输出写到每一行第二页的方法。 You probably would want to use a counter to do this. 您可能希望使用计数器来执行此操作。 This is an example of a sub that works - I'm not sure if it is what you want to do or if it helps you at all: 这是一个有效的子示例-我不确定这是您要执行的操作还是对您完全有帮助:

Sub Combination()

Dim jCell As Range
Dim kCell As Range
Dim result As String
Dim i As Integer
i = 1

Sheet2.Cells.Clear

For Each jCell In ActiveSheet.UsedRange
    For Each kCell In ActiveSheet.UsedRange
        result = jCell.Value & kCell.Value

        Sheet2.Cells(i, 1).Value = result

        i = i + 1

    Next kCell
Next jCell

End Sub

Good Luck. 祝好运。

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

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