将变量传递给Excel VBA中的加载项函数

时间:2014-05-27 21:44:23

标签: vba excel-vba excel

我想编写一个for循环,它接受每个单元格的值,将其传递给一个名为FixID()的函数,然后将函数的结果输出到单元格的值中。下面的代码将值传递给函数fine,但它不会将新值写入单元格。

Sub test()
Total_Rows = Cells(Rows.Count, 3).End(xlUp).Row
For Each C In Range("A3", "C" & Total_Rows )
   C = FixID(C.Value)
Next

End Sub

1 个答案:

答案 0 :(得分:1)

更新:这是一个快速的小例子,我把它放在一起测试这项技术,它按预期工作......

Option Explicit
Sub Test()

Dim MyRange As Range, Cell As Range
Dim Temp As String
Dim Total_Rows As Long

Total_Rows = Cells(Rows.Count, 3).End(xlUp).Row

Set MyRange = Range("A1:C" & Total_Rows)
For Each Cell In MyRange
    Cell.Value = AddShrimp(Cell.Value)
Next Cell

End Sub

'Bubba Gump Function
Public Function AddShrimp(InputValue As String) As String
    AddShrimp = InputValue & " Shrimp"
End Function

之前:before_script

之后:after_script

原始回复:确保定义您要迭代的Range,如下所示:

For Each C In Range("A3:C" & Total_Rows)
     C.Value = FixID(C.Value)
Next C

我可能会将Option Explicit添加到您的例程的顶部,并且也会预先声明所有变量(以防止混淆,与错字相关的错误等):

Option Explicit
Sub Test()

Dim Total_Rows As Long
Dim C As Range, TotalRange As Range

Total_Rows = Cells(Rows.Count, 3).End(xlUp).Row
Set TotalRange = Range("A3:C" & Total_Rows)

For Each C In TotalRange
    C.Value = FixID(C.Value)
Next C

End Sub