我是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”或“”的值,因此条件测试数组中是否包含任何内容。如果数组的一个元素被“1”占用 - 结果是Rej。只有当数组'Arr'的所有元素都包含“”时,我才希望结果为Vir。
我的问题是该函数没有写入'Result'单元格。有什么我做错了吗?我的问题是excel数组如何读取“”字符串?
任何帮助表示感谢。
答案 0 :(得分:1)
您的函数从不写入结果单元格,因为您实际上从未告诉它写入单元格。
此行Result = ws.Cells(Rngrow, 6).Value
仅将变量Result设置为代码运行时特定单元格中存在的值。
您的If
块只会重置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)来测试整个案例。您必须根据您的标准测试数组中的每个元素。