VBA错误:"调用的对象已与其客户端断开连接"

时间:2014-06-02 17:57:44

标签: excel vba excel-vba

我正在尝试编写一个宏,它将x / y坐标与它们所适合的省略号相匹配。我的代码中的“Else”行出现自动化错误。我已经审查了很多其他帖子,但我无法弄清楚我的代码有什么问题。非常感谢任何帮助。谢谢!

Private Sub CommandButton1_Click()
Dim XR As Integer
Dim XC As Integer
Dim YR As Integer
Dim YC As Integer
Dim areaR As Integer
Dim areaC As Integer
Dim hR As Integer
Dim hC As Integer
Dim kR As Integer
Dim kC As Integer
Dim aR As Integer
Dim aC As Integer
Dim bR As Integer
Dim bC As Integer
Dim angleR As Integer
Dim angleC As Integer
Dim matchR As Integer
Dim matchC As Integer
XR = 2
XC = 1
YR = 2
YC = 2
Do Until ThisWorkbook.Sheets("Sheet1").Cells(XR, XC).Value = ""
ThisWorkbook.Sheets("Sheet1").Activate
areaR = 2
areaC = 6
hR = 2
hC = 7
kR = 2
kC = 8
aR = 2
aC = 9
bR = 2
bC = 10
angleR = 2
angleC = 11
matchR = XR
matchC = 12
    Do Until ThisWorkbook.Sheets("Sheet1").Cells(hR, hC).Value = ""
        If (((((ThisWorkbook.Sheets("Sheet1").Cells(XR, XC).Value) _
             - (ThisWorkbook.Sheets("Sheet1").Cells(hR, hC).Value)) * _
             Cos((ThisWorkbook.Sheets("Sheet1").Cells(angleR, angleC).Value)) _
             + ((ThisWorkbook.Sheets("Sheet1").Cells(YR, YC).Value) - _
             (ThisWorkbook.Sheets("Sheet1").Cells(kR, kC).Value)) * Sin _
             ((ThisWorkbook.Sheets("Sheet1").Cells(angleR, angleC).Value))) ^ 2) _
             / ((Cells(aR, aC).Value) ^ 2)) + (((((Cells(XR, XC).Value) - _
             (Cells(hR, hC).Value)) * Sin((ThisWorkbook.Sheets("Sheet1").Cells _
             (angleR, angleC).Value)) - ((ThisWorkbook.Sheets("Sheet1").Cells(YR, YC).Value) _
             - (ThisWorkbook.Sheets("Sheet1").Cells(kR, kC).Value)) _
             * Cos((Cells(angleR, angleC).Value))) ^ 2) / ((Cells(bR, bC).Value) ^ 2)) _
             <= 1 Then
             ThisWorkbook.Sheets("Sheet1").Cells(matchR, matchC).Value = _
             ThisWorkbook.Sheets("Sheet1").Cells(areaR, areaC)
       Else
             areaR = areaR + 1
             hR = hR + 1
             kR = kR + 1
             aR = aR + 1
             bR = bR + 1
             angleR = angleR + 1
       End If
    Loop
   XR = XR + 1
   YR = YR + 1
Loop

End Sub

1 个答案:

答案 0 :(得分:0)

这是很多代码,使用单元格参考值进行直接数学运算很难阅读......甚至可能适合你。

这可能不是一个很好的答案,但如果你在循环中创建变量(是的,更多的变量),那么你的代码将更容易为每个人阅读,很可能你的错误会出现。

因此,不要在计算中使用ThisWorkbook.Sheets("Sheet1").Cells(XR, XC).Value,而应首​​先执行此操作:X = ThisWorkbook.Sheets("Sheet1").Cells(XR, XC).Value

但不要止步不前。包括将自我描述您的代码和计算过程的中间变量。

这有望让你看到它真正做的代码。

isMatch = cosX <= 1
If isMatch Then

顺便说一句,我的怀疑是你的错误来自于你没有使用工作表参考资格所有你的Cells方法。