我一直在尝试创建一个函数来检索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
答案 0 :(得分: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
答案 1 :(得分: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]
。