简体   繁体   English

使用excel VBA激活工作表

[英]Activate worksheet using excel VBA

I have a file "Workbook A" in a folder.我在一个文件夹中有一个文件“工作簿 A”。 An updated version is sent to me every fortnight.更新版本每两周发送给我。 I want to open this workbook from another workbook, "Workbook B" and at the same time delete blank rows in "Workbook A".我想从另一个工作簿“工作簿 B”打开此工作簿,同时删除“工作簿 A”中的空白行。

The opening and deleting operations will occur through the use of a macro.打开和删除操作将通过使用宏进行。

This is my code thus far.到目前为止,这是我的代码。

Sub RemoveEmptyRows()
    ' this macro will remove all rows that contain no data
    ' ive named 2 variables of data type string
    Dim file_name  As String
    Dim sheet_name As String

    file_name = "C:\Users\Desktop\Workstation_A\Workbook_A.xlsm"
    'Change to whatever file i want
    sheet_name = "Worksheet_A"   'Change to whatever sheet i want

    ' variables "i" and "LastRow" are needed for the for loop
    Dim i As Long
    Dim LastRow As Long

    ' we set wb as a new work book since we have to open it
    Dim wb As New Workbook

    ' To open and activate workbook
    ' it opens and activates the workbook_A and activates the worksheet_A
    Set wb = Application.Workbooks.Open(file_name)
    wb.Sheets(sheet_name).Activate

    ' (xlCellTypeLastCell).Row is used to find the last cell of the last row
    ' i have also turned off screen updating
    LastRow = wb.ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
    Application.ScreenUpdating = False

    ' here i am using a step
    ' the step is negative
    ' therefore i start from the last row and go to the 1st in steps of 1
    For i = LastRow To 1 Step -1
    ' Count A - Counts the number of cells that are not empty and the
    ' values within the list of arguments (wb..ActiveSheet.Rows(i))
    ' Afterwards deleting the rows that are totally blank
        If WorksheetFunction.CountA(wb.ActiveSheet.Rows(i)) = 0 Then
            wb.ActiveSheet.Rows(i).EntireRow.Delete
        End If
    Next i

    ' used to update screen
    Application.ScreenUpdating = True
End Sub

The work sheet name contains Worksheet_A as part of its name followed by a date.工作表名称包含Worksheet_A作为其名称的一部分,后跟日期。 For example Worksheet_A 11-2-15 .例如Worksheet_A 11-2-15

In my code, I have assigned the variable sheet_name to Worksheet_A在我的代码中,我已将变量sheet_name分配给Worksheet_A

sheet_name = "Worksheet_A" 

and further down I have used再往下我用过

.Sheets(sheet_name).Activate

to activate the worksheet.激活工作表。 I feel there is an issue with below line:我觉得下面这行有问题:

sheet_name = "Worksheet_A"

since sheet_name is not exactly Worksheet_A it only contains Worksheet_A as part of its name.因为sheet_name不完全是Worksheet_A它只包含Worksheet_A作为其名称的一部分。

This is causing a problem.The workbook A opens but the deleting of blank rows does not occur.这会导致出现问题。工作簿 A 已打开,但未删除空白行。
Further more an error message is displayed.此外,还会显示错误消息。

Run Time Error 9: Subscript out of Range.运行时错误 9:下标超出范围。

How do I modify my code so that the worksheet gets activated and the macro operations are performed?如何修改我的代码以便激活工作表并执行宏操作?

is it possible to solve this by using Like or Contain statements?
From your comment, yes.从你的评论来看,是的。 After opening the workbook, iterate the worksheet collection like this:打开工作簿后,像这样迭代工作表集合:

Dim sh As Worksheet
For Each sh In wb.Sheets
    If InStr(sh.Name, "WorkSheet_A") <> 0 Then
        sheet_Name = sh.Name: Exit For
    End If
Next

Or you can grab that object and work directly on it.或者您可以抓取该对象并直接对其进行处理。

Dim sh As Worksheet, mysh As Worksheet
For Each sh In wb.Sheets
    If InStr(sh.Name, "WorkSheet_A") <> 0 Then
        Set mysh = sh: Exit For
    End If
Next

LastRow = mysh.Cells.SpecialCells(xlCellTypeLastCell).Row
'~~> rest of your code here

If you only have one(1) Worksheet though, you can access it through index.如果您只有一 (1) 个工作表,则可以通过 index.html 访问它。

Set mysh = wb.Sheets(1)

You might find this POST interesting which discusses how to avoid Select/Activate/Active to further improve your coding in the future.您可能会发现这个POST很有趣,它讨论了如何避免选择/激活/活动以在将来进一步改进您的编码。 HTH.哈。

Here is your code tailored:这是您量身定制的代码:

Sub RemoveEmptyRows()
    Dim file_name  As String

    file_name = "C:\Users\Desktop\Workstation_A\Workbook_A.xlsm"
    Dim i As Long
    Dim LastRow As Long

    Dim wb As Workbook, mysh As Worksheet
    Set wb = Application.Workbooks.Open(file_name)
    'Above code is same as yours

    Set mysh = wb.Sheets(1) 'if only one sheet, use loop otherwise

    Application.ScreenUpdating = False
    Dim rngtodelete As Range
    With mysh
        LastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
        'Collect all the range for deletion first
        For i = LastRow To 1 Step -1
            If WorksheetFunction.CountA(.Rows(i)) = 0 Then
                If rngtodelete Is Nothing Then
                    Set rngtodelete = .Rows(i)
                Else
                    Set rngtodelete = Union(rngtodelete, .Rows(i))
                End If
            End If
        Next i
    End With
    'Delete in one go
    If Not rngtodelete Is Nothing Then rngtodelete.Delete xlUp
    Application.ScreenUpdating = True
End Sub

A sheet is .select, a workbook is .activate.工作表是 .select,工作簿是 .activate。

Try尝试

.Sheets(sheet_name).Select

Rather than deleting a row at a time I would reccomend you build a string or range and just do one bulk delete at the end.我建议您构建一个字符串或范围,然后在最后进行一次批量删除,而不是一次删除一行。 Here is an example to set you on your way:这是一个让您上路的示例:

Sub delete_rows()
Dim MyRows As String
For i = 27 To 1 Step -1
    If WorksheetFunction.CountA(ActiveSheet.Rows(i)) = 0 Then
        MyRows = MyRows & "$" & i & ":$" & i & ","
        'wb.ActiveSheet.Rows(i).EntireRow.Delete
    End If
Next i
MyRows = Left(MyRows, Len(MyRows) - 1)
Range(MyRows).Delete
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM