excel - VBA "Application defined or object defined error"

标签 excel vba

我有以下 VBA 代码行,旨在按标题名称查找列并将整个列作为一个范围:

Set w1 = wbk.Sheets("Sheet1")
Set parentRange = w1.Rows(1).Find("portfolioName").Offset(1).Resize(num_rows - 1, 1)

它在一个工作簿中工作得很好,但是当我在一个新工作簿中尝试它时,我收到以下错误:
<Application-defined or object-defined error>

我是 VBA 新手,所以我不确定是否显示代码上下文或提供更多详细信息,是否有一些简单的东西我可能会忽略?

行数:
num_rows = w1.Cells(Rows.Count, 1).End(xlUp).row

最佳答案

Dim f1 As Range, f2 As Range

Set w1 = wbk.Sheets("Sheet1")
'find first instance
Set f1 = w1.Rows(1).Find("portfolioName",lookat:=xlWhole)
If Not f1 Is Nothing then
    'find second instance
    Set f2 = f1.offset(0, 1).Resize(1, w1.Columns.Count - f1.Column).Find("portfolioName",lookat:=xlWhole)
    If not f2 is nothing then
        'set range based on f2
        Set parentRange = w1.Range(f2.Offset(1, 0), _
                                   w1.cells(rows.count,f2.column).end(xlup))

    end if
end if

在您发布的代码中,您从 ColA 获得了行数,但这似乎不可靠?在上面的代码中,它只选择搜索词的第二个实例下方的所有数据。

关于excel - VBA "Application defined or object defined error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51992608/

相关文章:

vba - 如何使用超链接(或通过将宏分配给超链接)在 Excel 中扩展组

excel - 遍历文件夹中的多个文件从特定工作表复制并粘贴到 MASTER 文件中

excel - 在创建 excel 工作表时使用分隔符 4gl

vba - 以编程方式添加工作簿事件并保存

vba - Excel VLookup "Object Required"错误

vba - 在 VBA 中创建带有集合的类

excel - 子函数显示用户窗体

vba - 在新页面部分中初始存在的 pdf 文件末尾添加打印区域内容(附加)

匹配类型 = -1 的 Excel MATCH 失败

excel - VBA 中的加权 Damerau-Levenshtein