【发布时间】:2021-08-28 13:50:53
【问题描述】:
我正在尝试运行一个执行三件事的宏:
- 循环遍历一系列 excel 文件
- 标识包含文本“项目属性”的行
- 使用此行设置范围以执行合并操作
我使用在其他地方找到的代码构建块构建了它,并且我知道每个代码块都是独立工作的(即我可以在不执行操作的情况下运行所有文件,并且我可以识别行并执行合并)但是当我组合他们,我得到一个运行时 91 错误“对象变量或未设置块变量”-与此行“FindRowNumber = FindRow.Row”相关联。
寻找有关如何避免将此变量设置为“无”的指导,因为它显示在“监视”窗口中。
谢谢!
'''
Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
'Change First Worksheet's Background Fill Blue
wb.Worksheets(1).Range("A1:Z1").Interior.Color = RGB(51, 98, 174)
Call RowStart(wb)
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Sub RowStart(wb As Workbook)
Dim FindRowNumber As Long, FindRowStart As Integer, FindRow As Range
With wb.Worksheets("Project Details")
Set FindRow = .Range("A:A").Find(What:="Project Attributes", LookIn:=xlValues, LookAt:=xlWhole)
End With
FindRowNumber = FindRow.Row
FindRowStart = FindRowNumber + 1
'MsgBox FindRowStart
Call vba_merge(FindRowStart, wb)
End Sub
【问题讨论】:
-
.find没有找到任何内容,因此返回了一个没有.row属性的空对象。
标签: excel vba loops file subroutine