背景:
我有一个电子表格作为报名表格。有许多输入字段,一个单元格中的字符串表示数量的标题,下面是单元格数量的值。
只有部分字段是强制性的。我正在尝试编写一个宏来遍历所有必填字段并确保存在一个值。
重要变量:
MandatoryValues =包含必填字段标题的字符串数组
MandatoryCount =必填字段数
FindString =字段标题为字符串
r =字段标题的行
c =字段标题的列
Check_Value =字段标题下方包含所需值
的单元格的值以下是我的代码:
For i = 1 To MandatoryCount
FindString = MandatoryValues(i - 1)
With ActiveSheet.UsedRange
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
r = Rng.Row
c = Rng.Column
Check_Value = ActiveSheet.Cells(r + 1, c).Value
data_type = TypeName(Check_Value)
If data_type = "String" Then
If Check_Value = "" Then
If MsgBox(FindString & " Not Specified", vbOKOnly, "ERROR") = vbOK Then
Exit Sub
End If
End If
End If
If data_type = "Double" Then
If Check_Value = "" Then
If MsgBox(FindString & " Not Specified", vbOKOnly, "ERROR") = vbOK Then
Exit Sub
End If
End If
End If
If data_type = "Date" Then
If Check_Value = 0 Then
If MsgBox(FindString & " Not Specified", vbOKOnly, "ERROR") = vbOK Then
Exit Sub
End If
End If
End If
Else
End If
End With
Next i
对于每个循环,我在工作表中搜索UsedRange以获取标题,并使用.Find定位其位置。这很好用。我的问题是,当我逐步执行代码时,我可以看到FindString,r和c随每次迭代而变化,但Check_Value总是为空。我觉得这是愚蠢的,但我看不到它。有什么建议?
编辑:我添加了代码段
If Not Rng Is Nothing Then
Address = Rng.Address
Address_Below = Rng.Offset(1, 0)
每次迭代都会更新Address值,并且正确查找工作表中的字符串并检索范围。但是,Address_Below变量始终为空。我不知道为什么会这样。有什么想法吗?
答案 0 :(得分:0)
假设 MandatoryValues (字符串数组)下方的单元格是Check_Value
,您应该考虑简化代码,如下所示(通过一些调整):
With ActiveSheet.UsedRange
'For i = 1 To MandatoryCount
For Each FindString In MandatoryValues
'FindString = MandatoryValues(i - 1)
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
' If error occurs you may use: What:=CStr(FindString)
If Not Rng Is Nothing Then
'r = Rng.Row
'c = Rng.Column
'Check_Value = ActiveSheet.Cells(r + 1, c).Value
Check_Value = Rng.Offset(1, 0).Value ' <-- Remove .Offset() if not checking the cell below it
'data_type = TypeName(Check_Value)
Select Case TypeName(Check_Value)
Case "String", "Double", "Date"
If Check_Value = "" Or Check_Value = 0 Then
If MsgBox(FindString & " Not Specified", vbOKOnly + vbExclamation, "ERROR") = vbOK Then Exit Sub
End If
Case Else
Debug.Print """" & FindString & """ at " & Rng.Address & " is of type " & TypeName(Check_Value)
End Select
End If
'Next i
Next
End With