Integer使Array返回错误的值

时间:2015-04-28 09:46:22

标签: excel-vba integer vba excel

我定义了以下数组:

Global Locations_Array() As String
ThisWorkbook.Worksheets("Locations").Activate
TotalRowsLocations = ActiveSheet.UsedRange.Rows.Count
ReDim Locations_Array(1 To TotalRowsLocations, 1 To 6) As String

根据这个,我希望数组的第一行是第1行。 我使用这个数组来命名工作簿中的新工作表,从1开始,到达应有的位置。

但是现在我再次使用以下代码调用此数组:

Sub Get_Lat_Lng()
    Dim row As Integer
    Dim data_row As Integer

    Call Fill_Array_Locations

    totalrowsdata = ThisWorkbook.Worksheets("Locations").UsedRange.Rows.Count - 1

    TotalRowsDataLookup = ThisWorkbook.Worksheets(Locations_Array(row, 1)).UsedRange.Rows.Count

    For row = 2 To totalrowsdata
        ThisWorkbook.Worksheets(Locations_Array(row, 1)).Activate
        If (UCase(Locations_Array(row, 5))) = (UCase(ThisWorkbook.ActiveSheet(row, 7))) And (UCase(Locations_Array(row, 6))) = (UCase(Worksheet.ActiveSheet(row, 8))) Then

            For data_row = 1 To TotalRowsDataLookup
                If (UCase(Locations_Array(row, 2)) = UCase(ThisWorkbook.Worksheets(Locations_Array(data_row, 1)).Cells(data_row, 5))) Then
                   Cells(data_row, 7) = Locations_Array(row, 5)
                   Cells(data_row, 8) = Locations_Array(row, 6)
                   Exit For
                End If
            Next data_row

            Exit For
       End If
    Next row
End Sub

它返回“运行时错误'9':下标超出范围” 当我检查此行代码中的值时,由于是整数,行的值为0。有没有办法让这个整数从1开始而不是0?我找到了设置选项:

Option Base 1

但这会干扰我的其余代码。

2 个答案:

答案 0 :(得分:2)

Dim row As Integer定义一个整数而不为其赋值,默认为row = 0。如果你想要一个不同的值,那么你必须在使用之前为它分配你想要的值。

尝试:

Dim row As Integer
row = 1

如果您的Location_Array的每一行都有totalrowsdata的数据,那么您的For Loop会将row = 2重新定义为起始值,并递增至totalrowsdata }。

了解更改对代码产生的影响的最佳方法是尝试并查看。如果它没有按您的想法工作,请尝试使用F8逐步浏览每一行并检查每个循环的row值。

答案 1 :(得分:0)

Sub Get_Lat_Lng()
    Dim row As Integer
    Dim data_row As Integer

    Call Fill_Array_Locations

    totalrowsdata = ThisWorkbook.Worksheets("Locations").UsedRange.Rows.Count - 1

    Row = 1 'Row should be at least 1

    '"Row" should be at least 1 before here.
    TotalRowsDataLookup = ThisWorkbook.Worksheets(Locations_Array(row, 1)).UsedRange.Rows.Count

    For row = 2 To totalrowsdata
        ThisWorkbook.Worksheets(Locations_Array(row, 1)).Activate
        If (UCase(Locations_Array(row, 5))) = (UCase(ThisWorkbook.ActiveSheet(row, 7))) And (UCase(Locations_Array(row, 6))) = (UCase(Worksheet.ActiveSheet(row, 8))) Then

            For data_row = 1 To TotalRowsDataLookup
                If (UCase(Locations_Array(row, 2)) = UCase(ThisWorkbook.Worksheets(Locations_Array(data_row, 1)).Cells(data_row, 5))) Then
                   Cells(data_row, 7) = Locations_Array(row, 5)
                   Cells(data_row, 8) = Locations_Array(row, 6)
                   Exit For
                End If
            Next data_row

            Exit For
       End If
    Next row
End Sub