我试图在一些excel文件中创建一个范围名称,然后将文件名和路径写入另一个excel。文件/路径被正确写入,但范围名称似乎并未在文件中创建。你能告诉我我要去哪里吗?在几个文件中创建范围名称
Sub directlisting()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim cell As Range
Dim RangeName As String
Dim CellName As String
Dim i As Integer
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("\\xxxxxxxxxxx\testdata\Transfer")
'loops through each file in the directory and prints their names and path
For Each objFile In objFolder.Files
'open file if an Excel file
If Right(objFile, 4) = "xls*" Or Right(objFile, 3) = "xl*" Then
Application.Workbooks.Open (objFile)
'create range name
RangeName = "PVS"
CellName = "A4:AG27"
Set cell = Worksheets("PVS").Range(CellName)
objFile.Names.Add Name:=RangeName, RefersTo:=cell
'Save the file
Application.DisplayAlerts = False
objFile.Save
objFile.Close
Application.DisplayAlerts = True
End If
'print file name
Cells(i + 1, 1) = objFile.Name
'print file path
Cells(i + 1, 2) = objFile.path
i = i + 1
Next objFile
End If
End Sub
尝试添加您设置单元格的工作簿名称为'..Workbooks(“MainBook.xlsx”)。Worksheets(“PVS”)。Range(cellName)'。它可能会抓住不正确的范围? – BruceWayne
感谢您的回复,BruceWayne。我有超过20000个excel工作簿,这就是我采取这种方法的原因。无论如何,如果它在循环的每次迭代中打开下一个工作簿,都不应该有必要吗? –
每个“objFile”都有一张名为“PVS”的表单吗?并且您正在尝试创建一个命名范围(在每个“objFile”中创建一个命名范围(名为“PVS”,范围为“A4:AG27”)? – BruceWayne