在Excel vba中移动相对范围

问题描述 投票:0回答:1

所以我试图在excel一个单元格中移动一个相对范围但是我在尝试这样做时遇到错误。我基本上有2个工作表。第二个包含几个带有主机名的单元格。每个主机名下面是更多具有位置名称的单元格。第一个工作表包含一个按钮,每当我点击该按钮时,它会要求我输入主机名和新位置。我们的想法是在第二个工作表中找到主机名,并将整个位置列表复制一个单元格而不触及实际主机名,以便我可以将新位置添加到主机名正下方的单元格而不会丢失任何数据。

到目前为止这是我的代码,它给了我一个错误:

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

除了我试图选择范围并将整个单元格向下移动的部分之外,一切都在工作。

我希望你们能指出我正确的方向。先感谢您!

编辑:

        '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

这些线条给我一个错误。

excel vba excel-vba
1个回答
0
投票

你的rangerng2在不同的床单上。

UPDATE

当您键入Range时,您可以有效地引用恰好处于活动状态的工作表,因此最好使用工作表名称限定Range。

© www.soinside.com 2019 - 2024. All rights reserved.