我正在尝试在列中搜索某个类别,然后在满足条件时将该类别更改为其他名称(如果它是我需要更改的类别)。我知道如何使用单个变量逐行遍历列,但是当我尝试将行和列的组合声明为数组(以加快循环)时,我会挂断。我是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"
答案 0 :(得分: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"
答案 1 :(得分:0)
要么更改Cell值:
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
答案 2 :(得分: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