宏和文本框代码疑难解答

2024-02-05

我有一个工作宏,它循环遍历文件夹以打开文件,并从名称“HOLDER”和“CUTTING TOOL”列中获取重要信息,并将所有信息打印到一个 Excel 文档(主文件)中。

我创建了一个带有/搜索按钮的文本框,我可以在其中输入一个文件名,它将转到该文件夹​​并打开该文件。

我正在尝试更改我的宏并将其放入搜索按钮的代码中,以从“HOLDER”列中获取重要信息和"CUTTING TOOL"并将其打印到 Excel 文档 masterfile 中。这是工作宏和我为搜索按钮量身定制的修改后的宏。

目前我陷入了更改宏的第 (3) 部分Set hc = HeaderCell(ws.Cells(ROW_HEADER, 1), "CUTTING TOOL")给出错误未设置对象变量或 With 块变量有任何想法吗?

UPDATE我以某种方式通过了Set hc = HeaderCell(ws.Cells(ROW_HEADER, 1), "CUTTING TOOL")第 (3) 节中的错误以及在第 (4) 节的类似行中弹出的另一个错误,同样的错误。现在我遇到了同样的错误,未设置对象变量或 With 块变量,在第(5)行中

StartSht.Cells(i, 1) = objFile.Name

我不确定这是否与那行代码有关,事实上它正在利用ws and .Worksheets,或者完全不同的东西。任何建议都会很棒!

改变的宏:

Option Explicit

Sub Search()

    Const ROW_HEADER As Long = 10

    Dim objFSO As Object
    Dim objFolder As Object
    Dim MyFolder As String
    Dim objFile As Object
    Dim WB As Workbook
    Dim dict As Object
    Dim i As Integer
    Dim StartSht As Worksheet, ws As Worksheet
    Dim hc As Range, hc1 As Range, hc2 As Range, hc3 As Range, d As Range

    Set StartSht = Workbooks("masterfile.xlsm").Sheets("Sheet1")

    Set hc1 = HeaderCell(StartSht.Range("B1"), "HOLDER")
    Set hc2 = HeaderCell(StartSht.Range("C1"), "CUTTING TOOL")

    'create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'get the folder object
    i = 2


'(2)

            'Open folder and file name, do not update links
            'Set WB = Workbooks.Open(fileName:=MyFolder & objFile.Name, UpdateLinks:=0)
            'Set ws = WB.ActiveSheet
'(3)
                'find CUTTING TOOL on the source sheet
                Set hc = HeaderCell(ws.Cells(ROW_HEADER, 1), "CUTTING TOOL")
                If Not hc Is Nothing Then

                    Set dict = GetValues(hc.Offset(1, 0))
                    If dict.count > 0 Then
                        Set d = StartSht.Cells(Rows.count, hc2.Column).End(xlUp).Offset(1, 0)
                        'add the values to the masterfile, column 3
                        d.Resize(dict.count, 1).Value = Application.Transpose(dict.items)
                    End If
                Else
                    'header not found on source worksheet
                End If
'(4)
                'find HOLDER on the source sheet
                Set hc3 = HeaderCell(ws.Cells(ROW_HEADER, 1), "HOLDER")
                If Not hc3 Is Nothing Then

                    Set dict = GetValues(hc3.Offset(1, 0))
                    If dict.count > 0 Then
                        Set d = StartSht.Cells(Rows.count, hc1.Column).End(xlUp).Offset(1, 0)
                        'add the values to the master list, column 2
                        d.Resize(dict.count, 1).Value = Application.Transpose(dict.items)
                    End If
                Else
                    'header not found on source worksheet
                End If
'(5)
            With WB
               'print TDS information
                For Each ws In .Worksheets
                        'print the file name to Column 1
                        StartSht.Cells(i, 1) = objFile.Name
                        'print TDS name from J1 cell to Column 4
                        With ws
                            .Range("J1").Copy StartSht.Cells(i, 4)
                        End With
                        i = GetLastRowInSheet(StartSht) + 1
                'move to next file
                Next ws
'(6)
                'close, do not save any changes to the opened files
                .Close SaveChanges:=False
            End With
    'turn screen updating back on
    Application.ScreenUpdating = True
    ActiveWindow.ScrollRow = 1
'(7)
End Sub

'(8)
'get all unique column values starting at cell c
Function GetValues(ch As Range) As Object
    Dim dict As Object, rng As Range, c As Range, v
    Set dict = CreateObject("scripting.dictionary")
    For Each c In ch.Parent.Range(ch, ch.Parent.Cells(Rows.count, ch.Column).End(xlUp)).Cells
        v = Trim(c.Value)
        If Len(v) > 0 And Not dict.exists(v) Then
            dict.Add c.Address, v
        End If
    Next c
    Set GetValues = dict
End Function

'(9)
'find a header on a row: returns Nothing if not found
Function HeaderCell(rng As Range, sHeader As String) As Range
    Dim rv As Range, c As Range
    For Each c In rng.Parent.Range(rng, rng.Parent.Cells(rng.Row, Columns.count).End(xlToLeft)).Cells
        If Trim(c.Value) = sHeader Then
            Set rv = c
            Exit For
        End If
    Next c
    Set HeaderCell = rv
End Function

'(10)
Function GetLastRowInColumn(theWorksheet As Worksheet, col As String)
    With theWorksheet
        GetLastRowInColumn = .Range(col & .Rows.count).End(xlUp).Row
    End With
End Function

'(11)
Function GetLastRowInSheet(theWorksheet As Worksheet)
Dim ret
    With theWorksheet
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            ret = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row
        Else
            ret = 1
        End If
    End With
    GetLastRowInSheet = ret
End Function

完整的宏:

    Option Explicit

Sub LoopThroughDirectory()

    Const ROW_HEADER As Long = 10

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim MyFolder As String
    Dim StartSht As Worksheet, ws As Worksheet
    Dim WB As Workbook
    Dim i As Integer
    Dim LastRow As Integer, erow As Integer
    Dim Height As Integer
    Dim RowLast As Long
    Dim f As String
    Dim dict As Object
    Dim hc As Range, hc1 As Range, hc2 As Range, hc3 As Range, d As Range

    Set StartSht = Workbooks("masterfile.xlsm").Sheets("Sheet1")

    'turn screen updating off - makes program faster
    Application.ScreenUpdating = False

    'location of the folder in which the desired TDS files are
    MyFolder = "C:\Users\trembos\Documents\TDS\progress\"

    'find the headers on the sheet
    Set hc1 = HeaderCell(StartSht.Range("B1"), "HOLDER")
    Set hc2 = HeaderCell(StartSht.Range("C1"), "CUTTING TOOL")

    'create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'get the folder object
    Set objFolder = objFSO.GetFolder(MyFolder)
    i = 2


    'loop through directory file and print names
'(1)
    For Each objFile In objFolder.Files
        If LCase(Right(objFile.Name, 3)) = "xls" Or LCase(Left(Right(objFile.Name, 4), 3)) = "xls" Then
'(2)

            'Open folder and file name, do not update links
            Set WB = Workbooks.Open(fileName:=MyFolder & objFile.Name, UpdateLinks:=0)
            Set ws = WB.ActiveSheet
'(3)
                'find CUTTING TOOL on the source sheet
                Set hc = HeaderCell(ws.Cells(ROW_HEADER, 1), "CUTTING TOOL")
                If Not hc Is Nothing Then

                    Set dict = GetValues(hc.Offset(1, 0))
                    If dict.count > 0 Then
                        Set d = StartSht.Cells(Rows.count, hc2.Column).End(xlUp).Offset(1, 0)
                        'add the values to the masterfile, column 3
                        d.Resize(dict.count, 1).Value = Application.Transpose(dict.items)
                    End If
                Else
                    'header not found on source worksheet
                End If
'(4)
                'find HOLDER on the source sheet
                Set hc3 = HeaderCell(ws.Cells(ROW_HEADER, 1), "HOLDER")
                If Not hc3 Is Nothing Then

                    Set dict = GetValues(hc3.Offset(1, 0))
                    If dict.count > 0 Then
                        Set d = StartSht.Cells(Rows.count, hc1.Column).End(xlUp).Offset(1, 0)
                        'add the values to the master list, column 2
                        d.Resize(dict.count, 1).Value = Application.Transpose(dict.items)
                    End If
                Else
                    'header not found on source worksheet
                End If
'(5)
            With WB
               'print TDS information
                For Each ws In .Worksheets
                        'print the file name to Column 1
                        StartSht.Cells(i, 1) = objFile.Name
                        'print TDS name from J1 cell to Column 4
                        With ws
                            .Range("J1").Copy StartSht.Cells(i, 4)
                        End With
                        i = GetLastRowInSheet(StartSht) + 1
                'move to next file
                Next ws
'(6)
                'close, do not save any changes to the opened files
                .Close SaveChanges:=False
            End With
        End If
    'move to next file
    Next objFile
    'turn screen updating back on
    Application.ScreenUpdating = True
    ActiveWindow.ScrollRow = 1
'(7)
End Sub

'(8)
'get all unique column values starting at cell c
Function GetValues(ch As Range) As Object
    Dim dict As Object, rng As Range, c As Range, v
    Set dict = CreateObject("scripting.dictionary")
    For Each c In ch.Parent.Range(ch, ch.Parent.Cells(Rows.count, ch.Column).End(xlUp)).Cells
        v = Trim(c.Value)
        If Len(v) > 0 And Not dict.exists(v) Then
            dict.Add c.Address, v
        End If
    Next c
    Set GetValues = dict
End Function

'(9)
'find a header on a row: returns Nothing if not found
Function HeaderCell(rng As Range, sHeader As String) As Range
    Dim rv As Range, c As Range
    For Each c In rng.Parent.Range(rng, rng.Parent.Cells(rng.Row, Columns.count).End(xlToLeft)).Cells
        If Trim(c.Value) = sHeader Then
            Set rv = c
            Exit For
        End If
    Next c
    Set HeaderCell = rv
End Function

'(10)
Function GetLastRowInColumn(theWorksheet As Worksheet, col As String)
    With theWorksheet
        GetLastRowInColumn = .Range(col & .Rows.count).End(xlUp).Row
    End With
End Function

'(11)
Function GetLastRowInSheet(theWorksheet As Worksheet)
Dim ret
    With theWorksheet
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            ret = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row
        Else
            ret = 1
        End If
    End With
    GetLastRowInSheet = ret
End Function

您修改的宏有错误。您离线评论(参见“(3)”部分):

'Set WB = Workbooks.Open(fileName:=MyFolder & objFile.Name, UpdateLinks:=0)

同时仍然使用这个变量WB稍后在代码中(参见“(5)”部分)

With WB

这就是为什么您收到“object var is not set”错误消息的原因。你必须修复这部分。希望这会有所帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

宏和文本框代码疑难解答 的相关文章

  • 无法在我的抓取工具中设置超时选项以防止无限循环

    我已经使用 IE 在 vba 中编写了一个脚本 在其搜索框中的网页中启动搜索 通过点击搜索按钮根据搜索填充结果 网页加载它是searchbox几秒钟后它就会打开 但是 我的下面的脚本可以处理这个障碍并以正确的方式执行搜索 现在 我有一个稍微
  • 在 Excel 表格中选择多列的代码

    我是 Excel VBA 新手 我需要修改我的代码 以便我能够进一步进行 我想在 Excel 表格中选择多个表格列 这是我的代码 Dim ws As Worksheet Dim tbl As ListObject Set ws Sheets
  • excel 2010刷新BackgroundQuery中运行时错误1004

    我正在尝试用 vba 编写一个脚本 用于将多个文本文件导入 Excel 一张纸 然后将它们绘制在一张图表上 我面临一个问题刷新后台查询命令并出现 1004 运行时错误 我怎样才能解决它 谢谢 埃亚勒 这是我的代码 Sub fring1 Di
  • 屏幕键盘显示时调整 winrt 页面大小

    我有一个 Windows 8 1 C 应用程序 它显示一个带有相当大文本框的页面 几乎覆盖整个页面 它是一个书写应用程序 当屏幕键盘出现时 它会覆盖文本框的一半 我想调整文本框 甚至整个页面 的大小 使其不被键盘覆盖 我现在尝试使用静态 I
  • VBA Shell 并等待退出代码

    我正在打包一个办公应用程序 VBA 它调用 C 控制台应用程序来执行应用程序 大型模拟程序 的一些繁重工作 我希望能够让 VBA 应用程序等待控制台应用程序完成并从控制台应用程序检索退出代码 我已经能够做到前者 但尚未能够从应用程序中检索退
  • 如何在 Excel 中对一组数据进行排序以匹配另一组数据?

    我有一个不按字母或数字顺序排列的数据列表 我想对同一日期的第二个列表进行排序以匹配第一个列表 我无法更改数据的顺序 我的目标是将第二组中的附加数据粘贴回第一个数据集中 DATA SET A DATA SET B 22350 BH160 10
  • 如何找到特定程序的安装目录?

    我已经成功地编写了一些用于工作的 VBA 宏 这些宏基本上创建了一个数据文件 将其提供给一个程序并对该程序的输出进行后处理 我的问题是程序安装路径是硬编码在宏中的 并且安装在我同事的计算机上可能会有所不同 我首先想到的是 我可以从每个人那里
  • VBA 有没有办法了解未使用的变量?

    标准 VBA 编辑器中是否有工具 方法或设置来警告已被修改的变量Dim med 但没有被使用 MZ Tools http www mztools com index aspx将搜索您的代码并告诉您哪些内容未被使用 VBA的版本可以找到her
  • JasperReports 中每个工作表属性一页

    我有一个要求 我必须在 JasperReports 中设计一个报告 该报告有 4 页 第一张纸有 5 页 类似的其他纸有一页或两页 我面临的问题是 如果我使用net sf jasperreports export xls one page
  • 我可以获取VBA代码中的注释文本吗

    可以说我有以下内容 Public Sub Information TEST End Sub 有没有办法得到 TEST 结果 不知何故通过VBA 例如 在 PHP 中 有一个获取注释的好方法 这里有什么想法吗 编辑 应该有办法 因为像 MZ
  • 在Excel中,我可以使用超链接来运行vba宏吗?

    我有一个包含多行数据的电子表格 我希望能够单击一个单元格 该单元格将使用该行中的数据运行宏 由于行数总是在变化 我认为每行的超链接可能是最好的方法 ROW MeterID Lat Long ReadX ReadY ReadZ CoeffA
  • 我如何以更好的方式编码而不是像这样的VBA编码

    我正在 Excel 中创建一个仪表板 但是我想知道是否有比这更好的编码方式 我想对其进行模块化 而不是这样做以使其更加整洁 Private Sub Afford If af Value True Then af afr Value Shee
  • 在VBA中初始化全局变量

    在 Excel 2003 中 如何声明全局变量并仅在打开工作簿时初始化它们一次 我有一些由几个宏使用的参数 基本上是输入文件的路径 目前 我的代码如下所示 global path1 path2 as string sub initPaths
  • 使用 FindElementbyXpath() 获取 Selenium Basic 中可填充框的行和列名称

    我正在使用 Selenium Basic 将电子表格中的文本填充到网站中 网站的html代码是这样的 div table cellspacing 0 border 1 style width 99 tr th style font weig
  • SQL Excel VBA 运行时错误 3709 无效连接

    这是我的第一个问题 欢迎提出建设性的批评 我正在尝试从 Excel VBA 查询 Access 数据库并将返回信息放入 Excel 范围中 我收到此错误 错误消息 运行时错误 3709 连接无法用于 执行此操作 在此情况下它已关闭或无效 语
  • 有没有更快的方法来使用Powershell解析Excel文档?

    我正在与一个接口MS Excel文件通过Powershell 每个 Excel 文档可能有大约 1000 行数据 目前这个脚本似乎读取了Excel文件并以每 0 6 秒 1 条记录的速率将值写入屏幕 乍一看 这似乎非常慢 这是我第一次阅读E
  • 使用 ADODB 连接从关闭的工作簿中检索数据。某些数据被跳过?

    我目前正在编写一些代码 可以通过 ADODB 连接访问单独的工作簿 由于速度的原因 我选择了这种方法而不是其他方法 下面是我的代码 Sub GetWorksheetData strSourceFile As String strSQL As
  • 使用 VBScript 在日期字段值上选择错误的数据

    我有一张包含以下数据的表 现在 Excel 共有 36 个任务 每个任务有 4 列 第一个任务 即 Task1 名称将始终从 L 列开始 144 列描述了 36 个任务 现在我们需要按行进行检查 并需要检查 TNStart 开始日期 你们能
  • 使用 split 函数到数组中会导致编译错误:无法分配给数组

    我正在尝试使用split 函数根据给定名称字符串中的空格拆分名称 当尝试编译我在下面编写的代码时 出现编译错误 无法分配给数组 我几乎从这里复制了微软的示例 https support microsoft com en us kb 2662
  • 使用PHP从doc、xls文件中读取数据

    我想知道是否可以从 doc 和 xls 文件中读取数据并将 将内容读取到图像文件中 创建文档的页面样本 例如 我有一些文件希望我的客户购买 所以我需要自动创建小图像 例如我的文档样本 我们将不胜感激您的帮助 对于读取 xls 文件 我真的推

随机推荐