Application.Caller / Storing worksheet name as string

时间:2018-07-24 10:16:41

标签: excel vba excel-vba

Im trying to store the CurrentWorksheet name in order to reference it in a different Sub routine.

The code I currently have is as follows:

Private Sub InsertNewBill_Click()
Dim rng As Range
Set rng = Worksheets(CurrentWorksheet).Range("A30:L30")
rng.Insert Shift:=xlDown
End Sub

Current Worksheet Function:

Function CurrentWorksheet()
CurrentSheet = Application.Caller.Worksheet.Name
End Function

I need to try to reference the "CurrentSheet" variable in the "InsertNewBill" Sub routine.

The function of this is to insert a new line of cells between "A30:L30" on the currently selected worksheet.

Thanks in advance

2 个答案:

答案 0 :(得分:0)

谢谢大家的帮助和指导。

我已经解决了以下问题

在按下按钮的一系列单元格之间插入新的单元格:

Private Sub InsertNewBill_Click()
Dim rng As Range
Set rng = Worksheets(CurrentWorksheet).Range("A31:AC31")
rng.Insert Shift:=xlDown
End Sub

当前工作表功能:

Function CurrentWorksheet()
CurrentWorksheet = ActiveSheet.Name
End Function

答案 1 :(得分:0)

我不打算将其写为答案,而是向Batteredburrito解释如何处理对象而不是名称:

Option Explicit

Private Sub InsertNewBill_Click()
    Dim rng As Range
    Set rng = currentWorksheet.Range("A31:AC31")
    rng.Insert Shift:=xlDown
End Sub

当前工作表功能

Function currentWorksheet() As Worksheet
    set currentWorksheet = ActiveSheet
End Function

这与您的版本完全相同(因此您可以坚持使用),只是为了展示如何处理对象。但是在某些情况下,最好使用带有名称的对象-尤其是当您处理多个工作簿(可能具有相同的工作表名称)时。

当然,最后,您只需编写即可完全摆脱该功能

...
Set rng = ActiveSheet.Range("A31:AC31")
...