我只对此进行了一点测试,所以它可能不是那么健壮。
注意此子需要放置在新的(或现有的)模块中,而不是任何工作表或此工作簿模块中。
它是一个宏,因此不能作为 UDF 从工作表中调用。此外,由于它有参数,因此不能直接调用。
要使用代码,您需要创建另一个子程序来为您调用它,或者直接从即时窗口调用它。
Sub RunCode()
Main "Name1", "Name2" ' you could run this line in the immediate/debug window
End Sub
该子RunCode
应该在您的工作簿的宏菜单中可用。
Sub Main(ByVal Name1 As String, ByVal Name2 As String)
Dim Cell As Long
Dim Range1 As Range: Set Range1 = ThisWorkbook.Names(Name1).RefersToRange
Dim Range2 As Range: Set Range2 = ThisWorkbook.Names(Name2).RefersToRange
' check to make sure Name1 and Name2 are the same size
If Range1.Cells.Count = Range2.Cells.Count Then
If Range1.Rows.Count = Range2.Rows.Count Then
If Range1.Columns.Count = Range2.Columns.Count Then
' populate the cells with the formula
For Cell = 1 To Range1.Cells.Count
Range2.Cells(Cell).Formula = "=" & Range1.Worksheet.Name & "!" & Range1.Cells(Cell).Address
Next Cell
End If
End If
End If
End Sub
如果您想要对该函数进行更多可定制的界面,那么以下代码应该会有所帮助。运行RunCode2
宏将提示您输入要传递给的两个名称Main
Public Function nameExists(ByVal Name As String) As Boolean
Dim Result As Boolean: Result = fasle
Dim Item As Variant
For Each Item In ThisWorkbook.Names
If Item.Name = Name Then
Result = True
Exit For
End If
Next Item
nameExists = Result
End Function
Sub RunCode2()
Dim Response As Variant
Dim Name1, Name2 As String
Response = Application.InputBox(Prompt:="Name 1", Type:=2)
If VarType(Response) = vbBoolean Then
Debug.Print "RunCode2 - User Canceled Name 1 Selection"
Exit Sub
Else
If nameExists(Response) = False Then
MsgBox "Name [" & Response & "] Not Found", vbOKOnly
Exit Sub
Else
Name1 = Response
End If
End If
Response = Application.InputBox(Prompt:="Name 2", Type:=2)
If VarType(Response) = vbBoolean Then
Debug.Print "RunCode2 - User Canceled Name 2 Selection"
Exit Sub
Else
If nameExists(Response) = False Then
MsgBox "Name [" & Response & "] Not Found", vbOKOnly
Exit Sub
Else
Name2 = Response
End If
End If
Main Name1, Name2
End Sub