Excel VBA“方法对象_工作表范围失败
我正在尝试做一些VBA编程,但遇到了一个奇怪的情况。 下面的代码在一个excel文件中运行正常,但没有另一个,标题中的错误出现在我分配SearchRange
variables的行中。
Private Sub Worksheet_Change(ByVal Target As Range) If Target.Address = "$B$3" Then Dim rngX As Range Dim counter As Integer Dim wsLeit As Excel.Worksheet Dim wsFilt As Excel.Worksheet Dim searchValue As String Dim searchRange As Range Dim rownr As String Set wsLeit = Excel.ThisWorkbook.Sheets("Leit") Set wsFilt = Excel.ThisWorkbook.Sheets("FILT") Set searchRange = wsFilt.Range("A4:ZZ10000") searchValue = wsLeit.Range("B3").Value Set rngX = searchRange.Find(what:=searchValue, lookat:=xlPart) wsLeit.Range("A6:B200").ClearContents If Not rngX Is Nothing Then strFirstAddress = rngX.Address counter = 8 rownr = Split(rngX.Address, "$")(2) For Each c In wsFilt.Range("A" & rownr & ":" & "ZZ" & rownr) If Not IsEmpty(c.Value) Then wsLeit.Range("A" & CStr(counter)).Value = c.Value foundColumn = Split(c.Address, "$")(1) wsLeit.Range("B" & CStr(counter)).Value = wsFilt.Range(foundColumn & "1").Value & " " & wsFilt.Range(foundColumn & "2").Value counter = counter + 1 End If Next Else MsgBox "Fann ekkert" End If End If End Sub
任何想法为什么这个代码工作在一个工作簿,而不是另一个? (两本书都有相同的名字)
EDIT1:
为了完整起见,这里是完整的错误:
Runtime Error '1004': Method 'Range' of object '_Worksheet' failed
问题是Excel 2007
以前版本的列数较less ,有时在文件格式更改时会产生随机故障。
一些Excel 2003规范:
Worksheet size 65,536 rows by 256 columns Column width 255 characters Row height 409 points Page breaks 1000 horizontal and vertical
Excel 2010:
Worksheet size 1,048,576 rows by 16,384 columns Column width 255 characters Row height 409 points Page breaks 1,026 horizontal and vertical Total number of characters that a cell can contain 32,767 characters
防止出现这种问题的一个好的做法是在Workbook_Open
事件中添加一个“guard”子例程,用于检查(使用Application.Version
)当前的excel版本是否为文件的最小版本。 您可以将最小的Excel版本存储在Workbook.Names
集合中作为常量,并检查该常量。
我希望这有帮助!