【发布时间】:2021-11-09 04:35:40
【问题描述】:
我正在努力创建将动态将未定义数量的变量粘贴到公式中的代码。我遇到问题的部分是我拥有的值的数量是未定义的,并且能够将值粘贴到公式中。
例子:
计算 A = (1 + 1) Ans = 2 公式 = 2
计算 B = (3 + 3) Ans = 6 公式 = 2 + 6
Calc C = (4 + 4) Ans = 8 公式 = 2 + 6 + 8
这种方法的好处是,当我点击公式时,我可以看到答案的审计线索。
下面的尝试代码
Dim Ans1 as Integer
Dim Ans2 as Integer
Ans1 = 2
Range("A1").Value = Ans1
Ans2 = 6
Range("A1").Formula = Ans1 + Ans2
更新:
Sub vba_loop_sheets()
Dim i As Long 'Base sheet
Dim ii As Long 'Moving sheet
Dim shtCount As Long
Dim ans As Variant
Dim ans2 As Variant
shtCount = Sheets.count - 1
For i = 7 To shtCount
For ii = i + 1 To shtCount
If Sheets(i).Range("B1").Value = Sheets(ii).Range("B1").Value And ans = "" Then
ans = Abs(Sheets(i).Range("B8").Value - Sheets(ii).Range("B8").Value)
ThisWorkbook.Sheets("calc").Range("F5").Value = ans
ElseIf Sheets(i).Range("B1").Value = Sheets(ii).Range("B1").Value And ans <> "" Then
ans2 = Abs(Sheets(i).Range("B8").Value - Sheets(ii).Range("B8").Value)
ans = ans + ans2
ThisWorkbook.Sheets("calc").Range("F5").Value = ans
End If
Next ii
Next i
End Sub
更新 09/14/21 下午 5:15
Sub vba_loop_sheets()
Dim i As Long 'Base sheet
Dim ii As Long 'Moving sheet
Dim shtCount As Long
Dim ans As Variant
Dim ans2 As Variant
shtCount = Sheets.count - 1
For i = 7 To shtCount
For ii = i + 1 To shtCount
If Sheets(i).Range("B1").Value = Sheets(ii).Range("B1").Value And ans = "" Then
ans = Abs(Sheets(i).Range("B8").Value - Sheets(ii).Range("B8").Value)
ThisWorkbook.Sheets("calc").Range("F5").Formula = "=" & ans
ElseIf Sheets(i).Range("B1").Value = Sheets(ii).Range("B1").Value And ans <> "" Then
ans2 = Abs(Sheets(i).Range("B8").Value - Sheets(ii).Range("B8").Value)
ThisWorkbook.Sheets("calc").Range("F5").Formula = "=" & ans & "+" & ans2
ans = ans + ans2
End If
Next ii
Next i
End Sub
【问题讨论】:
-
Range("A1").Formula = "=" & Ans1 & "+" & Ans2。但这听起来很像 XY 问题。 -
我面临的挑战是,有时可能有 2 个答案,有时 3 个,有时 4 个,有时更多,我希望它们都粘贴在公式中
-
好吧,如果我们的想法是能够看到答案的审计线索,为什么不直接对涉及求和的单元格进行着色,然后在任何工作表事件中更改回颜色代码?跨度>
-
好主意,但数据来自其他工作簿。
-
如果将其存储为一个值,它将被存储为一个值。如果要存储公式,则必须改用
Range.Formula,但我在您的更新中只看到Range.Value。
标签: excel vba excel-formula