将VBA宏转换为函数

问题描述 投票:0回答:2

我一直在尝试创建一个函数来检索excel表中第四行中的列标题。这是我到目前为止,有人可以帮助我吗?

 Sub Test_Click()
 Dim text As String
 Dim titles(200) As String
 Dim nTitles As Integer

 For i = 1 To 199
    If Trim(Sheets("Sheet1").Cells(4, i).Value) = "" Then
        nTitles = i - 1
        Exit For
    End If
    titles(i - 1) = Sheets("Sheet1").Cells(4, i).Value
 Next

 For i = 0 To nTitles
    Sheets("Sheet1").Cells(20 + i, 1).Value = titles(i)
 Next

 End Sub
vba excel-vba excel
2个回答
1
投票

就像你写一个Sub一样,你可以写一个Function,只需替换代码开头和结尾的单词。

现在,关于如何返回值,显然它将是一个数组,因此您需要声明数组,设置其大小,填充其单元格并返回它。这可以这样做:

Function  yourFunction() as String()
    ' You already have an array named "titles" which stores the values you want 
    ' to return. Fill it exactly as you do in your original code.
    yourFunction = titles ' This is the way to return the array.
End Function

如果要在工作表中使用此函数(作为公式),请记住这是一个数组函数,因此在单元格中输入函数后,您需要按Ctrl + Shitf + Enter,而不仅仅是[Enter]


2
投票

你需要为此创建一个数组函数。因此,您的功能将通过范围接收输入

Function ReturnArray(Input as Range) as Variant
    ' Do stuff with the Input range
    Dim Output(m,n) as Variant

    'Loop through m,n to fill in the output values as you would in a range
    ReturnArray = Output
End Function

当您在excel中输入函数时,在突出显示您想要输出的位置后在单元格中键入它并按下Ctrl-Shift-Return

© www.soinside.com 2019 - 2024. All rights reserved.