gpt4 book ai didi

vba - Excel VBA“对象_工作表的方法范围失败

转载 作者:行者123 更新时间:2023-12-03 02:48:11 25 4
gpt4 key购买 nike

我正在尝试进行一些 VBA 编程,但遇到了奇怪的情况。下面的代码在一个 Excel 文件中运行良好,但在另一个 Excel 文件中则不然,标题中的错误出现在我分配 SearchRange 变量的行中。

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

知道为什么这段代码在一个工作簿中有效但在另一个工作簿中无效吗? (两本书中的工作表名称相同)

编辑1:

为了完整起见,这里是完整的错误:

Runtime Error '1004':

Method 'Range' of object '_Worksheet' failed

最佳答案

问题在于 Excel 2007 之前的版本有 smaller number of columns ,当文件格式更改时,这有时会导致随机失败。

一些 Excel 2003 规范:

工作表大小 65,536 行 x 256 列
列宽 255 个字符
行高409点
水平和垂直分页符 1000

Excel 2010:

工作表大小 1,048,576 行 x 16,384 列
列宽 255 个字符
行高409点
水平和垂直分页符 1,026
单元格可包含的字符总数 32,767 个字符

防止此问题的一个好做法是在 Workbook_Open 事件中添加一个“guard”子例程,用于检查(使用 Application.Version)当前的 Excel 版本是该文件的最小目标值。您可以将最低 Excel 版本作为常量存储在 Workbook.Names 集合中,并对照该常量进行检查。

希望这会有所帮助!

关于vba - Excel VBA“对象_工作表的方法范围失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23954502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com