参考工作表

问题描述 投票:0回答:2

所以我在提到工作表时遇到了问题。每当我在整个工作簿中的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

问候

excel vba loops
2个回答
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行,但如果你有一个标题行,你可能需要改变它。

然后,您将选择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

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
© www.soinside.com 2019 - 2024. All rights reserved.