数组计算后不写入所需单元的函数; excel vba用户表单

我是vba新手,需要一些帮助。 我有一个函数的作用是写一个单元格的文本值取决于一定的条件。

input到函数将是从用户窗体中的combobox获得的string。 行列式是53个单元格的数组,其值为“1”或“”。

Function State(ID As String, Rowarray() As String) Dim ws As Worksheet Dim Rej As String Dim Vir As String Dim Result As Variant Dim Rng Dim Rngrow As Integer Dim Arr Set ws = ThisWorkbook.Worksheets("Temp") Set Rng = ws.Columns(5).Find(ID).Address 'obtains the address of a cell with a value matching the combobox value. Rngrow = ws.Range(Rng).row 'Obtains the row number from address above Rej = "R" Vir = "V" Arr = Rowarray() Result = ws.Cells(Rngrow, 6).Value 'this cell is where output is to be placed - one column adjacent to the ID cell (same row) 'conditional statements determining what goes into result cell If Len(Arr) >= 1 Then Result = Rej ElseIf Len(Arr) < 1 Then Result = Vir Else Result = Vir End If End Function 

由于数组“Arr”只有“1”或“”的值,条件testing数组是否有任何内容。 如果数组中的一个元素被“1”占据 – 结果是Rej。 只有当数组“Arr”中的所有元素都包含“”时,我才需要结果为Vir。

我的问题是该函数不写入“结果”单元格。 有什么我做错了吗? 是我的问题如何Excel数组读取string?

任何帮助赞赏。

你的函数永远不会写入结果单元格,因为你实际上从来没有告诉它写入单元格。

此行Result = ws.Cells(Rngrow, 6).Value仅将variablesResult设置为代码运行时特定单元格中存在的值。

你的If块然后重置Resultvariables。

看下面的代码,我认为这更符合你想要的。 我添加了代码循环访问数组并检查1 ,然后根据数组中的内容在结果单元格中设置值。 我还添加了更好的variables符合types匹配。 我也做了这个Sub因为它不会返回任何值,就像一个Function一样。

 Sub State(ID As String, Rowarray() As String) Dim ws As Worksheet Dim Rej As String, Vir As String Dim Rng As Range Dim Rngrow As Integer Dim Arr() As String Set ws = ThisWorkbook.Worksheets("Temp") Set Rng = ws.Columns(5).Find(ID) 'obtains the cell with a value matching the combobox value. If Not Rng Is Nothing Then Rngrow = Rng.Row 'Obtains the row number from range above Rej = "R" Vir = "V" Arr() = Rowarray() Dim l As Long, bRej As Boolean For l = LBound(Arr) To UBound(Arr) If Arr(l) = "1" Then ws.Cells(Rngrow, 6).Value = Rej bRej = True Exit For End If Next If Not bRej Then ws.Cells(Rngrow, 6).Value = Vir Else ws.Cells(Rngrow, 6).Value = "id not found" End If End Sub 

还有一点需要注意,因为每个数组都有一个元素,所以我循环了数组。 即使那个元素= "" 。 所以你不能只用Len(Arr)来testing整个案例。 您必须根据您的标准testing数组中的每个元素。