使用.Select捕获来自不同工作表的数据

时间:2019-06-12 12:47:45

标签: excel vba

我必须在不同的excel表之间跳转,以获取数据以便VBA输出所需的数据。我一直在使用Sheets(“ name”)。Select函数在图纸之间跳转。有时它可以正常运行,并允许我运行程序,但有时我会遇到运行时错误。我希望此功能每次都能100%地正常工作,并且每次由于select函数而失败时,总会感到沮丧。如果有人有任何提示或建议,我希望与您分享!任何帮助将不胜感激。

self.runner.get_fact_cache(host)['ip_address']

运行时错误'1004':选择工作表类的方法失败

2 个答案:

答案 0 :(得分:1)

请勿使用Select(或Activate),这是不好的做法,并且会很快导致错误。

This thread对于为什么以及如何避免使用它提供了很大的帮助。

从表中获取数据之前无需选择表。例如:

Sub test()
'''
'Bad practise:
'''
Sheets("Sheet1").Select
i = Range("A1")

'''
'Good practise
'''
i = Workbooks("Book1").Sheets("Sheet1").Range("A1").Value

'''
'Better practise
'''
Dim wb As Workbook
Dim sht As Worksheet
Dim i As String

Set wb = Workbooks("Book1")
Set sht = wb.Sheets("Sheet1")

With sht
    i = .Range("A1").Value
End With

End Sub

答案 1 :(得分:0)

带有语句:

Option Explicit

Sub test()

    'Create a witrh statement with the Sheet name you want
    With ThisWorkbook.Worksheets("Sheet1")
        'Refer to cell A1 (don t forget the "." before Range)
        .Range("A1").Value = ""
        'Refer to cell A1 (don t forget the "." before Cells)
        .Cells(1, 1).Value = ""
    End With

End Sub

循环工作表:

Option Explicit

Sub test()

    Dim ws As Worksheet

    'Loop Sheets
    For Each ws In ThisWorkbook.Worksheets

        With ws
            'If sheet name is Sheet1 or Sheet3
            If .Name = "Sheet1" Or .Name = "Sheet3" Then

                'Refer to cell A1 (don t forget the "." before Range)
                .Range("A1").Value = 2
                'Refer to cell A1 (don t forget the "." before Cells)
                .Cells(1, 1).Value = 10
            ElseIf .Name = "Sheet2" Then
                'Refer to cell A1 (don t forget the "." before Range)
                .Range("A1").Value = 5
                'Refer to cell A1 (don t forget the "." before Cells)
                .Cells(1, 1).Value = 20

            End If

        End With

    Next ws

End Sub

将工作表设置为变量

Option Explicit

Sub test()

    Dim ws1 As Worksheet, ws2 As Worksheet

    With ThisWorkbook
        Set ws1 = .Worksheets("Sheet1")
        Set ws2 = .Worksheets("Sheet2")
    End With

End Sub