Excel VBA新手,尝试嵌套循环并出现编译错误
我是Excel VBA新手,对代码进行了双重和三重检查,但似乎仍然找不到问题。 我试图遍历一列(a),并创建一个列C中的值和一个介于1和6MIL之间的随机数串联的唯一标识符。我也在迭代C列 提前感谢您的帮助 这是我的密码:Excel VBA新手,尝试嵌套循环并出现编译错误,excel,vba,compiler-errors,Excel,Vba,Compiler Errors,我是Excel VBA新手,对代码进行了双重和三重检查,但似乎仍然找不到问题。 我试图遍历一列(a),并创建一个列C中的值和一个介于1和6MIL之间的随机数串联的唯一标识符。我也在迭代C列 提前感谢您的帮助 这是我的密码: Sub unique_id() Dim c As Range For Each i In Range("A:A") For Each x In Range("C:C") If IsNull(i.Value) = Tr
Sub unique_id()
Dim c As Range
For Each i In Range("A:A")
For Each x In Range("C:C")
If IsNull(i.Value) = True Then
i.Value = Concat(x.Value, RandBetween(1, 6000000))
End If
End If
Next x
Next i
End Sub
您的代码中有一些内容需要解决:
- 您正在对2列中的所有单元格进行嵌套循环(即每个循环的计算量超过10000000000000000),正如您所想,这不是最好的方法,而是在开始时设置范围
- 正如评论中指出的那样,正确地调暗所有变量
- 我假设通过使用
函数,您是在暗示单元格中没有值?在这种情况下,最好使用IsNull()
if val=“”,然后使用
- 您需要考虑错误检查,其中一部分是,如果您要创建唯一的ID,则需要检查它们是否真的是唯一的(是否已经存在)
Sub unique_ID()
Dim c As Range
Dim rng As Range
Dim uniqueID As String
Dim dupeFlag As Boolean 'flag to check for duplicate IDs
Set rng = Intersect(ActiveSheet.UsedRange, ActiveSheet.Columns("C")) 'goes through only the cells which have been used
For Each c In rng.Cells
If CStr(c.Offset(, -2).value) = "" Then 'checks if col A has any value inside
dupeFlag = True 'turns flag on for the while loop
Do While dupeFlag
uniqueID = c.value & Application.WorksheetFunction.RandBetween(1, 6000000) 'create the unique ID
If findDuplicate(uniqueID, rng.Offset(, -2)) = False Then 'checks if the ID already exists
c.Offset(, -2) = uniqueID 'if ID doesn't exist then then write it to col A
dupeFlag = False 'flag turns off to go to next cell
End If
Loop
End If
Next
End Sub
Function findDuplicate(val As String, srchRng As Range) As Boolean
'function to check if a duplicate is found in a range (the above macro calls it)
Dim cell As Range
For Each cell In srchRng.Cells
If cell.value = val Then
findDuplicate = True
Exit Function
End If
Next
findDuplicate = False
End Function
在内部循环中有多余的
End If
。编译器具体抱怨什么?如果您试图在VBA中使用工作表函数,则需要使用Application.functionme()
或Application.Worksheetfunction.FunctionName()
,这可能也是使用Option Explicit
的一个好习惯,这将迫使您声明所有变量。您将c声明为范围,而不使用它。您使用未声明的范围i
和x
。您是否知道,对于范围内的每个i(“A:A”)将循环通过A列中的所有1048576单元格,对于每个i,循环通过C列中的1048576单元格,循环总数为1048576*1048576?这是Excel无法计算的数字(溢出错误)。如果我是编译器,我也会抱怨.BTW,IsNull(I.Value)
不太可能是真的。坦率地说,我不知道Excel是否接受在其单元格中存储Null
值IsEmpty()
可能是更好的选择。但是Null
、Empty
和Nothing
具有非常精确的含义。当您仍在切割VBA牙齿时,请使用简单的If i.Value=“”,然后
我在randbween
函数上得到一个编译错误,因为我使用的是旧版本的Excel。