运行代码时,VBA方法'对象范围'_Worksheet突然失败了吗?

时间:2013-11-15 18:24:51

标签: excel vba excel-vba

这段代码以前运行正常,然后突然间它开始失败了“方法”范围的对象'_Worksheet失败'? “ 我不是VBA的专家,但我可以自己解决它。有什么我想念的吗?

Public Sub Run_Count_Click()

'// Set Ranges
Dim Cr_1, CR1_range, _
Cr_2, CR2_range, _
Cr_3, CR3_range, _
Cr_4, CR4_range, _
Cr_5, CR5_range _
As Range

'// Set Integers
Dim CR1, V1, CR1_Result, _
CR2, V2, CR2_Result, _
CR3, V3, CR3_Result, _
CR4, V4, CR4_Result, _
CR5, V5, CR5_Result, _
total_result, _
total_result2, _
total_result3, _
total_result4, _
total_result5 _
As Integer

'Set Strings
Dim V_1, V_2, V_3, V_4, V_5 As String

Dim ws As Worksheet



Set ws = Worksheets("database")

'// Get Criteria From Form And Search Database Headers
Set Cr_1 = ws.Cells.Find(What:=Me.Count_Criteria_1.Value, After:=Cells(1, 1), MatchCase:=False)

If Not Cr_1 Is Nothing Then

CR1 = Cr_1.Column '//Set CR1 as the Column in which the Criteria Header was found

Else
    MsgBox "Criteria 1 Has Not Been Found In The Database. Report Has Failed To Generate"
    Exit Sub
End If

'// Get Variable Value From Form And Set Shortcode
V_1 = Me.Criteria_1_Variable.Value


Set CR1_range = ws.Range(Cells(5, CR1), Cells(Rows.count, CR1))
CR1_Result = Application.CountIf(CR1_range, V_1)

If Me.Count_Criteria_2 = "Any" Then

Me.Count_Result.visible = True

Me.Count_Result.Value = "Based On Your Search Criteria Of:" & vbNewLine & _
"How many occurences of [" & Me.Criteria_1_Variable.Value & "] in the category [" & Me.Count_Criteria_1.Value & _
"] have occured between the dates..." & vbNewLine & vbNewLine & "The Results Are: " & CR1_Result

Exit Sub

代码在此行上失败:

Set CR1_range = ws.Range(Cells(5, CR1), Cells(Rows.count, CR1))

先谢谢你们

3 个答案:

答案 0 :(得分:30)

正在从活动表中引用单元格,而不是“数据库”。

Set CR1_range = ws.Range(ws.Cells(5, CR1), ws.Cells(ws.Rows.count, CR1))

答案 1 :(得分:1)

Excel VBA方法对象_global的范围是否失败?

$( '<div class="my_list" id="sam">' ).insertBefore($( ".my_list" ).first());

答案 2 :(得分:0)

我遇到了同样的错误信息,但原因对我来说不同。我只引用活动工作表。显然,我的一些用户都使用相同的VBA逻辑更改了默认的ReferenceStyle。不确定这是否是应用程序更新的结果,或者是否有多个用户设法进行相同的更改。调试逻辑我发现PrintArea表示不再转换为Range。

wS.Range(wS.PageSetup.PrintArea).Address

PrintArea值已填充,但以我不熟悉的格式显示。原来它是R1C1样式而不是默认的A1样式单元格引用。我发现另一篇文章引用了在用户设置中更改引用样式但我不想强制对用户进行更改。我决定每次打开时为此工作簿设置引用样式。我迷上了Workbook_Open并使用了xlA1。

Application.ReferenceStyle = xlA1