宏和文本框代码疑难解答

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(使用前将#替换为@)

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

  • OpenArgs 为空问题

    我正在使用OpenArgs使用时发送值的参数DoCmd OpenForm DoCmd OpenForm frmSetOther acNormal acFormAdd acDialog value 然后我用Me OpenArgs在打开的表格内
  • 在 VBA 中循环合并单元格

    是否可以循环遍历合并的单元格vba questions tagged vba 我的范围内有 6 个合并单元格B4 B40 我只需要这 6 个单元格中的值 6 次迭代 上面的答案看起来已经让你排序了 如果您不知道合并的单元格在哪里 那么您可以
  • 字典、集合和数组的比较

    我正在尝试找出字典与集合和数组相比的相对优点和功能 我发现了一篇很棒的文章here http www experts exchange com articles 3391 Using the Dictionary Class in VBA
  • VBA根据单元格的值是否为零显示/隐藏行

    我有一个 Excel 工作表 我想根据另一个单元格中的值隐藏或取消隐藏某些行 简而言之 整个事情应该取决于单元格中的值C2 D2 E2 If C2 is blank我想rows 31 to 40被隐藏 如果是的话不为空 他们需要是visib
  • Confluence:使用 VBA 更新现有页面

    我尝试使用 VBA 更新 Confluence 页面 我的想法是使用REST API加载页面内容 修改内容然后上传修改后的版本 这是我的代码 Private Sub TestRESTApi Dim uname As String uname
  • Word通过vba宏删除tabe列出现错误

    我想将excel中的数据复制到word表中 然后从表中删除一些列 我可以将数据复制到表中 但是当我删除列时会出现错误 无法访问此集合中的各个列 因为该表具有混合的单元格宽度 我的代码 Public Tbl1 As Table Sub cal
  • 无法将 Excel 值的类型“double”转换为“string”

    我正在加载 Excel 文件 如网络上许多地方所示 OpenFileDialog chooseFile new OpenFileDialog chooseFile Filter Excel files xls xlsl xls xlsx i
  • 复制一张工作表上的静态范围,然后根据单元格中的单个值粘贴到另一张工作表中的动态范围

    我对这个问题分为三个部分 我在 Sheet1 A1 中有一个带有周数的单元格 我在 Sheet1 B1 F1 中有一个需要复制的静态范围 然后 我需要将该值粘贴到 Sheet2 中的动态范围中 偏移量为行的周数 这是我正在为我经常使用的工作
  • 使用 Apache POI Excel 写入特定单元格位置

    如果我有一个未排序的参数 x y z 列表 是否有一种简单的方法将它们写入使用 POI 创建的 Excel 文档中的特定单元格 就好像前两个参数是 X 和Y 坐标 例如 我有如下行 10 4 100 是否可以在第 10 行第 4 列的单元格
  • 根据单元格值向用户窗体添加复选框

    我对 VBA 很陌生 只有 3 天 但我发现它非常有用且易于使用 但现在我面临一个问题 我需要制作一个具有不同复选框的用户窗体 但我需要根据工作表某一列中使用的信息自动添加它们 我相信我可以使用 For Each Next 但我真的不知道如
  • 检测 TextBox 中的 Tab 键按下

    I am trying to detect the Tab key press in a TextBox I know that the Tab key does not trigger the KeyDown KeyUp or the K
  • 如何使用VBA根据条件删除Excel中的行?

    我目前正在构建一个宏来格式化数据表并删除不适用的数据行 具体来说 我希望删除列 L ABC 的行以及删除列 AA DEF 的行 到目前为止 我已经实现了第一个目标 但还没有实现第二个目标 现有代码是 Dim LastRow As Integ
  • 在 VBA Excel 中查找、剪切和插入行以匹配借项和贷项值

    我在 Sheet1 中有以下设置数据 并从第 4 行 A 列开始 其中标题位于第 3 行 No Date Code Name Remarks D e b i t Cr e d i t 1 4 30 2015 004 AB 01 04 15
  • 如何将 MySQL 查询输出保存到 Excel 或 .txt 文件? [复制]

    这个问题在这里已经有答案了 如何将 MySQL 查询的输出保存到 MS Excel 工作表 即使只能将数据存储在 txt文件 就可以了 From 将 MySQL 查询结果保存到文本或 CSV 文件中 http www tech recipe
  • Excel工作簿关闭后反复打开

    我使用了 Application ontime 方法来调度一些宏 关闭工作簿后 它会一次又一次地打开 为了解决这个问题 我在工作簿上设置了另一个事件 BeforeClosed 现在它显示运行时错误 1004 Object Applicati
  • Excel:#CALC!使用 MAP 函数计算间隔重叠时出现错误(嵌套数组)

    我正在努力解决以下公式 它适用于某些情况 但不适用于所有情况 名字input有失败的数据集 得到一个 CALC 描述 嵌套数组 错误 LET input N1 0 0 N1 0 10 N1 10 20 names INDEX input 1
  • VBA在多个文件夹中搜索特定子文件夹并移动其中的所有文件

    你能帮助我吗 我想要一个宏vba来搜索SPECIFIC例如 所有存在并移动其文件的文件夹和子文件夹之间的子文件夹 Xfolder P Desktop Folder1 subfolder SUBFOLDER1 Xfolder 我正在使用 VB
  • Redim Preserve 给出“下标超出范围”

    我想要Redim Preserve一个数组我不断收到错误 下标超出范围 我知道只有最后一个维度的大小可以更改 这正是我正在做的事情 这里出了什么问题 数组的类型是Variant BmMatrix Sheets BENCH Range a60
  • 启动时的 Excel 加载项

    我正在使用 Visual C 创建 Microsoft Excel 的加载项 当我第一次创建解决方案时 它包含一个名为 ThisAddIn Startup 的函数 我在这个函数中添加了以下代码 private void ThisAddIn
  • 使用宏打开受信任文档或启用宏时 Excel 崩溃

    正如标题所示 我无法使用宏打开受信任的文档 Excel 立即崩溃 制作文档的副本允许其打开 因为该副本不受信任 并且我可以检查 VB 编辑器中的宏 但启用宏会导致另一次崩溃 为什么会发生这种情况以及我可以采取什么措施来解决它 我今天遇到了类

随机推荐