我只测试了一下,所以它可能不是那么强大。
注意该子部分需要放置在新的(或现有的)模块中,而不是放置在任何工作表或本工作簿模块中。
这是一个宏,因此不能作为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
可以使用公式属性,只需将单元格引用添加到第二你的第一张。您可能需要遍历范围内的每个单元格。 – NickSlash 2013-04-23 12:29:12
那么,为什么你不使用'= Sheet2!A1'? – user2140261 2013-04-23 13:09:30
为什么不使用'myrange.formula = myrange.formula'? http://msdn.microsoft.com/en-us/library/office/ff838835.aspx – glh 2013-04-23 13:11:24