gpt4 book ai didi

arrays - 函数未写入数组计算后所需的单元格; excel vba 用户表单

转载 作者:行者123 更新时间:2023-12-04 20:41:05 25 4
gpt4 key购买 nike

我是 vba 新手,需要一些帮助。
我有一个函数,其作用是根据特定条件向单元格写入文本值。

'函数的输入将是从用户窗体中的组合框获得的字符串。 Rowarray 是一个包含 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's”或“”的值,因此条件测试数组中是否有任何内容。如果数组的一个元素被“1”占据 - 结果是 Rej。只有当数组“Arr”的所有元素都包含“”时,我才希望结果为 Vir。

我的问题是该函数没有写入“结果”单元格。有什么我做错了吗? excel数组如何读取“”字符串是我的问题吗?

任何帮助表示赞赏。

最佳答案

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

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

您的 If block 然后只是重置Result多变的。

请参阅下面的代码,我认为它更符合您的要求。我添加了代码来循环遍历数组并检查 1 ,然后根据数组中的内容设置结果单元格中的值。我还添加了更好的变量限定来匹配类型。我也把它做成了 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) 来测试整个案例。您必须根据您的标准测试数组中的每个元素。

关于arrays - 函数未写入数组计算后所需的单元格; excel vba 用户表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33347580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com