2017-12-27 11 views
0

그래서 하나의 셀을 Excel에서 상대 범위를 이동하려고하는데 이렇게하려고하면 오류가 발생합니다. 기본적으로 2 개의 워크 시트가 있습니다. 두 번째 호스트 이름에는 두 개의 셀이 있습니다. 각 호스트 이름 아래에 위치 이름이있는 셀이 더 있습니다. 첫 번째 워크 시트에는 단추가 포함되어 있으며이 단추를 클릭 할 때마다 호스트 이름과 새 위치를 묻습니다. 두 번째 워크 시트에서 해당 호스트 이름을 찾고 실제 호스트 이름을 건드리지 않고 한 위치의 전체 목록을 복사하여 데이터를 잃지 않고 호스트 이름 바로 아래의 셀에 새 위치를 추가 할 수 있습니다.Excel에서 상대 범위 이동

이 내 지금까지 나에게 오류를 제공하는 코드입니다

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 

사람들은 나에게 오류를주는 라인입니다.

+0

어떤 라인 오류가 있습니까? 사진이 없으면 알 수 없습니다. – JohnyL

+0

원래 게시물에 오류가있는 줄을 편집했습니다. – hypestar

+0

'범위'와 'rng2'는 서로 다른 시트에 있습니다. – JohnyL

답변

0

rangerng2은 서로 다른 시트에 있습니다.

UPDATE

당신이 Range를 입력 할 때, 당신은 효과적으로 활성화 될 일 중 시트를 참조, 그래서 시트 이름과 범위를 한정하는 것이 좋습니다.