私はこれを少ししかテストしていないので、それほど堅牢ではないかもしれません。
注:このサブルーチンは、新しい (または既存の) モジュールに配置する必要があり、シートまたは thisworkbook モジュールのいずれにも配置する必要はありません。
これはマクロであるため、ワークシートから 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
と、渡す 2 つの名前を入力するよう求められます。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