testing丢失信息的可变范围数据并通知提交者

我是VBA的新手,是从别人的代码开始构build的,比VBA更新一些。 预先感谢您提供的任何提示和build议。

由于我无法发布图像,我将尝试描述数据集。 数据来自用户表单,其中大部分内容位于表格范围A14:M34中,列A中有问题,列BM中有数据。 第一行是用户填充的用于标识被检查单元的标题。 下面的数据填充空白,是和NO作为选项,以及一些数字或string的行。

我想testing每个单元格的大小范围可变,以便回答问题,并通知用户是否有任何问题,并在提交之前给他们select完成数据集的选项。


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)生成标题行的最后一个填充列,那么它们不是空白的,所以不需要testing。 尽pipe如此,我仍然保留我没有使用的代码,直到最后的检查完成,并且certificate它是完全无用的。 过多的评论是帮助一大批非VBA员工在执行之前跟踪和validation我的代码。

所以LastColumn定义似乎工作,我稍后再使用它。 当我遍历代码时,它会循环执行我的假数据集正确的次数。 我觉得这是空的是我倒下的地方。

如果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 

莱恩线的错误? 也许,因为Cells有2个参数? Cells(RowIndex,ColumnIndex)

另外,你可以通过设置LastColumn:

 LastColumn = ActiveSheet.UsedRange.Columns.Count 

行可以做同样的事情:

 LastRow = ActiveSheet.UsedRange.Rows.Count 

也许你应该移动If AbortProc Then Exit Sub里面的For循环(作为第一/最后一行)