对象相关的错误

我是VBA的新手,在学习期间,我在不同的行上得到了两种不同的错误,同时引用了现有工作表的值放在新工作表上:

对于这部分代码,我收到错误“Object variable or With block variable not set”,

Dim ws1 As Worksheet For Each wss In ThisWorkbook.Sheets If wss.Name = "Optimisation" Then found = True wss.Delete Exit For End If Next If Not found Then Set ws1 = ActiveWorkbook.Worksheets.Add ws1.Name = "Optimisation" End If ws1.Cells(1, 1).Value = "RECIPE" '<----- error 'ws1.Range(“A1”).Value = “RECIPE” <----- same error 

有时,当我运行代码时,我得到另一个错误,而不是上面的错误。 对于这部分代码,我收到错误“运行时错误:对象必需”

 Dim ws2 As Worksheet Set ws2 = Application.ActiveSheet Dim Newrecipe As String Newrecipe = ws2.Cells(currentrow, currentcolumn).Value '<----- error 

我试着set NewRecipe = ws2.Cells(currentrow, currentcolumn).Value来响应错误。 但是,现在我得到一个“编译错误:对象需要”为:

 Dim ws2 As Worksheet Set ws2 = Application.ActiveSheet Dim Newrecipe As String set Newrecipe = ws2.Cells(currentrow, currentcolumn).Value '<----- error 

有人可以向我解释为什么这些错误正在发生? 谢谢。

我认为第一个错误可能是因为你的代码没有运行下面的代码。

 Set ws1 = ActiveWorkbook.Worksheets.Add ws1.Name = "Optimisation" 

只有当()中的代码为真时, If () Then才会执行。 在你的情况下,你Not found 。 所以,如果你有一张名为“优化”的工作表,那么你需要设置“ found = true ,然后你才会问“找不到”。 如果found = true那么Not found = false 。 既然你有错误,你的if语句里面的代码就不会执行。

而对于你的第二个错误,你绝对不会使用set,因为一个string是VB的一个本地types的variables。 它的特定对象,通常需要使用set。 几乎任何数字,string,数组(变体),布尔值,date不需要设置。 我确定还有其他的我不知道,但只是想想如果你看到这种types的variables用不同的语言,你可能不需要一个集合。

我会更新我的答案,当我弄清楚为什么你会得到没有设置的错误。

只是一个问题, currentcolumncurrentcolumn在哪里初始化?

而不是循环遍历所有工作表,直接find现有工作表。

下面的代码还可以防止向用户发送警告消息(抑制DisplayAlerts)。

 Sub Recut() Dim ws1 As Worksheet On Error Resume Next Set ws1 = Sheets("Optimisation") On Error GoTo 0 If Not ws1 Is Nothing Then 'if found delete without alert Application.DisplayAlerts = False ws1.Delete Application.DisplayAlerts = True Else Set ws1 = ActiveWorkbook.Worksheets.Add ws1.Name = "Optimisation" ws1.Cells(1, 1).Value = "RECIPE" End If End Sub