找出具有=工作表名称的单元格地址

时间:2016-04-09 08:00:02

标签: excel vba excel-vba

我只是VBA的初学者,但在MS excel中取得进步。这就是为什么我对学习VBA非常感兴趣的原因。 好的,这是我的第一个问题

实际上我需要格式化excel表格,其中文件名是= sheet1 name,它位于列#34; A"所以我想选择&删除此单元格上方的所有行&在下面,直到有一个空白单元格/行。

我在InStr&找功能却没有成功。也尝试找到像B5这样的单元格地址,但不能这样做。

1 个答案:

答案 0 :(得分:0)

欢迎使用StackOverflow。正如你已经被newguy告知的那样,在发布问题时你还应该展示你到目前为止所尝试的内容......一些代码,打印屏幕等等。

你的解释不是那么清楚(至少对我而言),但根据我的理解,我为你做了一个小代码示例,让你开始。我已将代码分解为功能块,以便您可以更好地理解他们想要实现的目标。

以下是代码:

'the following function will find cell with the specific text
Private Function FindCell(ws As Worksheet, strToSearch As String, Optional sColumn As String = "A") As Integer
    Dim iCounter As Integer

    'as you do not know where exactly it exists, we loop from first cell in the particular row
    'to the very last celll
    With ws
        For iCounter = 1 To .Range("A65000").End(xlUp).Row ' or .UsedRange.Rows.Count, or any other method
            If .Range(sColumn & iCounter).Value = strToSearch Then
                'yay, we have found the cell!
                'pass out the reference
                FindCell = iCounter

                'now call exit function as we no longer need to continue searching for the cell (we have already found it!)
                Exit Function
            End If
        Next iCounter
    End With

    'in case the cell does not exist, we can return -1
    FindCell = -1
End Function

'the following cell will search the very first cell to the top (starting from specific row), which is blank / empty
Private Function FindEmptyCell(ws As Worksheet, iStartRow As Integer, Optional sColumn As String = "A") As Integer
        'This function does the same, as if you have selected specific cell
        'and then pressed left Ctrl + Up arrow at the same time
        'Try it!
        'You can do the same with Right + Left + Bottom arrow as well
        FindEmptyCell = ws.Range(sColumn & iStartRow).End(xlUp).Row + 1
End Function

Private Sub EraseRows()
    Dim iStartCell As Integer
    Dim iEndCell As Integer
    On Error GoTo 0
    'First let's find the "bottom" cell which is the cell with the specific text you are looking for
    iEndCell = FindCell(ActiveSheet, "TextIAmLookingFor")

    'now let's see find the top blank cell (so that we get the range of from - to that you want to erase)
    iStartCell = FindEmptyCell(ActiveSheet, iEndCell)

    'now we can delete the rows!
    'iEndCell-1 because you don't want to erase the cell with your search string, right?
    ActiveSheet.Rows(CStr(iStartCell) & ":" & CStr(iEndCell - 1)).EntireRow.Delete (xlUp)
End Sub