问题
So I've been fussing with the Microsoft Support answer to this question but their code is simply not working. I'm confused about how they do not define x, or maybe x always equals a variable in VBA? Anyway, I am trying to copy all named ranges in one workbook and bring them over to another workbook. I have to do this for 50-odd workbooks and there are 30-40 named ranges in the base workbook. I really do not want to have to copy-paste these buggers manually. Here's the code they gave for this problem:
Sub Copy_All_Defined_Names()
' Loop through all of the defined names in the active
' workbook.
For Each x In ActiveWorkbook.Names
' Add each defined name from the active workbook to
' the target workbook ("Book2.xls" or "Book2.xlsm").
' "x.value" refers to the cell references the
' defined name points to.
Workbooks("trial run.xlsm").Names.Add Name:=x.Name, _
RefersTo:=x.Value
Next x
End Sub
Running this gives me the following error:
and highlights the following code:
"trial run.xlsm" is just a blank workbook and is saved as macro-enabled; this is my target workbook. Seems silly to have to ask for help debugging a macro that microsoft wrote, but I'm kinda at the end of my rope here.
For the original page I got this from, see here: Microsoft Support
This is what my named ranges look like:
回答1:
Hard to tell but I suspect that your RefersTo string is >256 characters: If so it will fail because VBA cannot handle refersto strings>256 characters.
来源:https://stackoverflow.com/questions/49538753/copy-all-named-ranges-to-another-workbook