2

我正在尝试搜索某个类别的列,然后在满足条件时将该类别更改为不同的名称(如果它是我需要更改的类别)。我知道如何使用单个变量逐行遍历列,但是,当我尝试将行和列的组合声明为数组(以加快循环)时,我被挂断了。我是 VBA 新手,过去没有使用过数组。以下是我到目前为止的代码。

Dim myArray(1 To 1000, 3 To 3)
Dim i As Integer

For i = 1 To 1000
 myArray(i, 3) = Worksheets("Sheet1").Cells(i, 3)

 Next i

If myArray(i) = "Category1" Then
myArray(i) = "DifferentCategory"
4

3 回答 3

0

您的阵列使用情况不一致。如果您所做的只是更改名称,则无需使用多维数组:

假设您的代码是您所拥有的,那么以下应该可以工作:

Dim myArray(1 To 1000)
Dim i As Integer

For i = 1 To 1000
 myArray(i) = Worksheets("Sheet1").Cells(i, 3)

 Next i

If myArray(i) = "Category1" Then
myArray(i) = "DifferentCategory"
于 2012-11-16T12:01:56.697 回答
0

您想更改单元格值:

Dim i As Integer

For i = 1 To 1000
   If Worksheets("Sheet1").Cells(i, 3).Value2 = "Category1" Then
       Worksheets("Sheet1").Cells(i, 3).Value2 = "DifferentCategory"
    End If
 Next i

或者您希望myArray更改局部变量 ( ) 以便在您的代码中进一步使用:

Dim myArray(1 To 1000) As String
Dim i As Integer

For i = 1 To 1000
    MyArray(i) = Worksheets("Sheet1").Cells(i, 3).Value2 
    If MyArray(i) = "Category1" Then
       myArray(i) = "DifferentCategory"
    End If
 Next i
于 2012-11-16T12:40:39.877 回答
0

以下 1 班轮将执行您在第一句话中解释的内容:

Range(Worksheets("Sheet1").Cells(1, 3), Worksheets("Sheet1").Cells(1000, 3)).Replace "Category1", "DifferentCategory"

或者更容易阅读的版本:

Dim targetRange As Range
With Worksheets("Sheet1")
    Set targetRange = .Range(.Cells(1, 3), .Cells(1000, 3))
    targetRange.Replace "Category1", "DifferentCategory"
End With

如您所见,数组不是必需的,因为您正在寻找一个值并替换它。

但是,如果您真的想使用数组,这是更快的方法之一:

Dim myArray
Dim i As Integer
With Worksheets("Sheet1")
    'myArray will now be a (1 to 1000, 1 to 1) array with all the cell values.
    myArray = .Range(.Cells(1, 3), .Cells(1000, 3))
End With
For i = 1 To 1000
    If myArray(i, 1) = "Category1" Then myArray(i, 1) = "DifferentCategory"
Next
于 2012-11-16T13:59:31.980 回答