我尝试创建一个带有2个输入框的宏,通过第一个输入框,用户选择将其写入每个单元格C或D(贷方或借方)的范围 通过第二个输入,用户可以选择一个范围,在该范围内每个单元上将写入相应的数量。
我要做的是以下事情:
如果贷方/借方范围内的对应单元格的值是“ D”,则对应的单元格(我是指与此借方对应的金额)保持正值,否则变为负数。
例如,如果用户在J列中选择一个C / D范围,然后用户通过第二个输入框在B列中选择了所有对应的金额,我希望如果J1 =“ D”返回一个B1中为正值,否则对其他所有行在B1中返回负值,依此类推...
我尝试执行我的宏,但无法正常工作,我收到错误消息#NAME?
...
请在执行宏之前和之后找到以下2张屏幕截图以及VBA代码
如果有人可以帮助我,那就太好了。
Sub ReturncorrectsignofamountaccordingtoDorC()
Dim c As Range
Dim WorkRng2 As Range
Dim WorkRng As Range
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Please select the range D/C", xTitleId, WorkRng.Address, Type:=8)
Set WorkRng2 = Application.Selection
Set WorkRng2 = Application.InputBox("Please select the range of amounts", xTitleId, WorkRng.Address, Type:=8)
For Each c In WorkRng2
c.FormulaR1C1 = _
"=IF(c.WorkRng.value=""D"",c.WorkRng2.value= c.WorkRng2.value, c.WorkRng2.value= -c.WorkRng2.value)"
Next c
End Sub
答案 0 :(得分:3)
问题是您在字符串中混入了vba。您需要拉出vba并进行连接:
Range("A1").Formula = "=SUM(" & Range("A2").Address & ")"
引用c.WorkRng.value
也不正确。 c
是范围对象,而不是WorkRng
的父对象
您尝试插入的公式也是循环的,会引起很多问题,只需将值乘以1
或-1
Sub ReturncorrectsignofamountaccordingtoDorC()
Dim c As Range
Dim WorkRng2 As Range
Dim WorkRng As Range
Set WorkRng = Application.InputBox("Please select the range D/C", Type:=8)
Set WorkRng2 = Application.InputBox("Please select the range of amounts", Type:=8)
For Each c In WorkRng2
c.Value = c.Value * IIf(c.Offset(0, WorkRng.Column - c.Column).Value = "D", 1, -1)
Next c
End Sub
我个人将使用变体数组来加快速度:
Sub ReturncorrectsignofamountaccordingtoDorC()
Do
Dim WorkRng As Range
Set WorkRng = Application.InputBox("Please select the range D/C", Type:=8)
Dim WorkRng2 As Range
Set WorkRng2 = Application.InputBox("Please select the range of amounts", Type:=8)
If WorkRng.Cells.Count <> WorkRng2.Cells.Count Then MsgBox "Ranges must be same size"
Loop Until WorkRng.Cells.Count = WorkRng2.Cells.Count
Dim rng1 As Variant
rng1 = WorkRng.Value
Dim rng2 As Variant
rng2 = WorkRng2.Value
Dim i As Long
For i = LBound(rng1, 1) To UBound(rng1, 1)
rng2(i, 1) = rng2(i, 1) * IIf(rng1(i, 1) = "D", 1, -1)
Next i
WorkRng2.Value = rng2
End Sub