我是VBA的新手并且建立了别人的代码,VBA比我更新!提前感谢您提供的任何提示和建议。
由于我无法发布图像,因此我将尝试描述数据集。数据来自用户表单,其中大部分内容在表A14:M34中,在A列中有问题,在B-M列中有数据。第一行是用户填充的标题,用于标识检查的单元。下面的数据填充了下拉空白,是和否作为选项,以及几行数字或字符串。
我希望在可变大小的范围内测试每个单元格以查找未答复的问题,并在有任何问题时通知用户,并在提交之前为他们提供完成数据集的选项。
Sub new_p()
Static AbortProc As Boolean
Dim iRow As Long
Dim LastColumn As Long
Dim aCol As Long
Dim ws As Worksheet, WS1 As Worksheet
Dim InputRange As Range
Set ws = Worksheets("PreparationData")
Set WS1 = Worksheets("ColdWeatherPreparation")
Set InputRange = WS1.Range("B15:M34")
If AbortProc Then Exit Sub
'find last column in range
LastColumn = WS1.Cells(14, 2).End(xlToRight).Column
'define variable range of columns
For aCol = 2 To LastColumn
'check that the circuit row is not blank
'If Cells(14, aCol) Is Not Nothing Then
If IsEmpty(InputRange) Then
Msg = "All fields are not populated. Stop submission to resume editing?"
Ans = MsgBox(Msg, vbYesNo)
'if yes stop process
If Ans = vbYes Then
AbortProc = True
Exit Sub
End If
'if no run rest of script
If Ans = vbNo Then
MsgBox "Run without Correcting?"
AbortProc = False
Exit Sub
End If
End If
'End If
Next
'more code here that seems to be working
End Sub
你会看到我已经评论出一条我觉得多余的一条线。如果End(xlToRight)生成标题行的最后一个填充列,则它们不是空白,因此无需测试。尽管如此,在完成最终检查之前,我保留了我不使用的代码,并且证明它完全没用。过度评论是为了帮助一大群非VBA工作人员在实施之前跟踪并验证我的代码。
所以LastColumn定义似乎有效,我稍后会再次使用它。当我单步执行代码时,它会为我的虚假数据集循环正确的次数。我觉得isEmpty就是我倒下的地方。
答案 0 :(得分:0)
如果B15:M34中的每个单元格都应该是非空白的,那么您可以这样做:
If Application.CountBlank(InputRange)>0 Then
If Msgbox(Msg, vbYesNo) = vbYes Then
'rest of your code
End If
End If
编辑:这将根据相应的标题单元格检查每个数据单元格。
Sub new_p()
Static AbortProc As Boolean
Dim iRow As Long
Dim LastColumn As Long
Dim aCol As Long
Dim ws As Worksheet, WS1 As Worksheet
Dim InputRange As Range, rw As Range
Dim HeaderRange As Range
Dim x As Long, Msg As String
Set ws = Worksheets("PreparationData")
Set WS1 = Worksheets("ColdWeatherPreparation")
Set HeaderRange = WS1.Range("B14:M14")
Set InputRange = WS1.Range("B15:M34")
'are you sure about this next line?
'once validation has failed once how does it re-run?
If AbortProc Then Exit Sub
For Each rw In InputRange.Rows
For x = 1 To rw.Cells.Count
If Len(rw.Cells(x).Value) = 0 And _
Len(Headerange.Cells(x).Value) > 0 Then
Msg = "All fields are not populated. Stop submission" & _
" to resume editing?"
If MsgBox(Msg, vbYesNo) = vbYes Then
AbortProc = True
Exit Sub
Else
MsgBox "Run without Correcting?"
AbortProc = False
Exit Sub
End If
End If
Next x
Next rw
'more code here that seems to be working
End Sub
答案 1 :(得分:0)
Len线上的错误?也许,因为Cells有2个参数? Cells(RowIndex,ColumnIndex)
。
此外,您可以通过以下方式设置LastColumn:
LastColumn = ActiveSheet.UsedRange.Columns.Count
可以为行做同样的事情:
LastRow = ActiveSheet.UsedRange.Rows.Count
也许你应该将If AbortProc Then Exit Sub
移到For循环中(作为第一行/最后一行)