したがって、1つのセルをExcelで相対範囲を移動しようとしていますが、エラーが発生しています。 私は基本的に2つのワークシートを持っています。 2番目のセルには、ホスト名を持つ2つのセルが含まれています。各ホスト名の下には、より多くのセルが配置されています。 最初のワークシートにはボタンが含まれています。そのボタンをクリックするたびに、ホスト名と新しい場所を求められます。 2番目のワークシートにそのホスト名を見つけ、実際のホスト名に触れることなくそのセル全体をコピーして、データを失うことなくホスト名の直下のセルに新しい場所を追加できるようにします。Excel vbaで相対範囲を移動する
これは私にエラーを与える、これまでに私のコードです:
Sub UpdateLocation(hostname As String, newLocation As String)
Dim rng1 As range
Dim rng2 As range
Dim tmpRng As range
Dim oldLocation As String
'find cells in both sheets
Set rng1 = FindCellInSheet(hostname, "ServerListe")
Set rng2 = FindCellInSheet(hostname, "History")
If Not rng1 Is Nothing And Not rng2 Is Nothing Then 'were both cells found?
'change values in first sheet
oldLocation = rng1.Offset(0, 1).Value
rng1.Offset(0, 1).Value = newLocation
rng1.Offset(1, 4).Value = oldLocation
'change values in second sheet
If Not IsEmpty(rng2.Offset(1, 0)) Then 'is there a history record yet?
'select whole record until first empty cell
Set tmpRng = range(rng2.Offset(1, 0), rng2.End(xlDown))
'move content one cell down
range(rng2.Offset(2, 0), rng2.Offset((1 + tmpRng.Rows.count), 0)).Value = tmpRng.Value
End If
'insert oldLocation into history
rng2.Offset(1, 0).Value = oldLocation
Else
'in case one or both cells weren't found
MsgBox "'" & hostname & "' wurde nicht gefunden oder ist nur in einer Tabelle vorhanden."
End If
End Sub
Private Function FindCellInSheet(searchString As String, sheetName As String) As range
If Not IsEmpty(Trim(searchString)) Then 'remove spaces and check if cell is empty
With Sheets(sheetName).UsedRange 'selects all cells with content
'find searchString in specified sheet, case insensitive
Set FindCellInSheet = .Find(What:=searchString, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
End With
End If
Exit Function
End Function
すべては私が範囲を選択し、全体の多く一つのセルを下に移動しようとする部分以外finde取り組んでいます。
私はあなたが正しい方向に私を指すことができることを願っています。 ありがとうございます!
編集:
'select whole record until first empty cell
Set tmpRng = range(rng2.Offset(1, 0), rng2.End(xlDown))
'move content one cell down
range(rng2.Offset(2, 0), rng2.Offset((1 + tmpRng.Rows.count), 0)).Value = tmpRng.Value
それらは私にエラーを与え線です。
どのラインエラーが出力されますか?いくつかの写真なしで伝えるのは難しいです... – JohnyL
私は元の投稿に私にエラーを与える行を編集しました。 – hypestar
あなたの 'range'と' rng2'は別のシートにあります。 – JohnyL