所以我在提到工作表时遇到了问题。每当我在整个工作簿中的B列上找到一个空单元格时,我打算打开一个输入框,这样我就可以输入并更改空单元格值。
但是,我收到一个错误(首先是说订阅超出范围,我更改了它,所以现在它说应用程序/对象定义错误)在这一行:
For i = 0 To Sheets(j).Cells(Rows.Count, i).End(xlUp).Row
代码:
Dim Country As Variant
Dim Capital As Variant
Dim CapitalValue As Variant
Dim i As Integer
Dim j As Integer
' Select *first line of data*
Range("B1").Select
' Loop to stop when an empty cell is reached.
For j = 1 To Worksheets.Count
j = ActiveSheet.Index
Range("B1").Select
For i = 0 To Sheets(j).Cells(Rows.Count, i).End(xlUp).Row
'Select the Country Cell
ActiveCell.Offset(i, 0).Select
CapitalValue = ActiveCell.Value
'If Country is empty
If CapitalValue = "" Then
MsgBox ("No more Capitals")
Else
'Input Capital values
CapitalValue = ActiveCell.Value
Country = ActiveCell.Offset(0, -1).Value
Capital = InputBox("Capital of " & Country, "Capital Input")
CapitalValue = Capital
End If
Next i
Next j
此致
答案 0 :(得分:0)
在宏的顶部,将工作表设置为类似
的名称Dim a as worksheet
Set a = Sheets("yoursheetname")
然后,当您想要引用该特定表时,请使用
a.Range("a1").select
假设您的空白值在A栏中,我会执行类似
的操作Sub findBlanks()
Dim a As Worksheet
Set a = Sheets("Sheet1")
For x = 2 To a.Range("a1048576").End(xlUp).Row 'find last row
If a.Range("a" & x).Value = "" Then
MsgBox ("This cell is blank!!!")
End If
Next x
End Sub
答案 1 :(得分:0)
如果您想在所有工作表中重复此操作(如For j = 1 to Worksheets.Count
行所示),您不应该在j
的下一行中更改ActiveSheet.Index
,尤其是你的代码在任何时候都没有真正改变工作表。
您的Range("B1").Select
建议您想要在B列上循环查找这些值,因此请将For i = 0 To Sheets(j).Cells(Rows.Count, i).End(xlUp).Row
替换为For i = 1 To Sheets(j).Cells(Sheets(j).Rows.Count, "B").End(xlUp).Row
,因为您需要知道从哪里开始i
。我假设第1行,但如果您的标题行为2,则可能需要更改它。
然后,您正在选择activecell下方的单元格i
行。这是第一次围绕循环,这将使你从第2行移动到第3行。第二次你将从3跳到5,因为我从1增加到2.最好尽可能避免Select
无论如何,它会减慢速度。既然您已经注意到要查找空白值然后提示用户输入详细信息,我建议您改为:
For j = 1 to Worksheets.Count
For i = 1 To Sheets(j).Cells(Sheets(j).Rows.Count, "B").End(xlUp).Row
If Sheets(j).Range("B" & i).Value = "" Then
Country = Sheets(j).Range("A" & i).Value
Sheets(j).Range("B" & i).Value = InputBox("Please enter the capital for country " & Country, "Capital Input")
End If
Next
Next