VBA设置ActiveSheet的范围而不是A1:B2

时间:2017-06-02 17:29:25

标签: excel vba excel-vba spreadsheet

我是VBA中的菜鸟 我的数据范围从Row1到 Row 226 ,尝试将其导出为逗号分隔的csv文件。

Sub Comma()

Dim r As Range: Set r = Range("A1:D4") 
Dim buffer As String, delimiter As String, c As Range
Dim i As Long

我想将Range设置为当前工作表" Sheet1"

当我Dim r As Range: Set r = Range("Sheet1")时,它会向我抛出一个错误,而我似乎无法找到我想要的东西。

任何人都可以帮助我吗?谢谢

3 个答案:

答案 0 :(得分:3)

您需要找到最后一行,然后构建您的范围。请参阅This链接

Sub Sample()
    Dim ws As Worksheet
    Dim lastrow As Long
    Dim rng As Range

    Set ws = Sheets("Sheet1")

    With ws
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            lastrow = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row
        Else
            lastrow = 1
        End If

        Set rng = .Range("A1:D" & lastrow)
    End With
End Sub

如果您的最后一列也未修复,请使用此

Sub Sample()
    Dim ws As Worksheet
    Dim lastrow As Long, lastCol As Long
    Dim rng As Range
    Dim colName As String

    Set ws = Sheets("Sheet1")

    With ws
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            lastrow = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row

            lastCol = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByColumns, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Column
        Else
            lastrow = 1: lastCol = 1
        End If

        colName = Split(Cells(, lastCol).Address, "$")(1)

        Set rng = .Range("A1:" & colName & lastrow)
    End With
End Sub

答案 1 :(得分:2)

请尝试以下代码,因为良好做法始终使用模块顶部的Option Explicit

Option Explicit

Sub Comma()

Dim r As Range
Dim LastCell As Range
Dim LastRow As Long

Dim buffer As String, delimiter As String, c As Range
Dim i As Long

With Worksheets("Sheet1")
    ' get dynamic last row
    Set LastCell = .Cells.Find(What:="*", After:=Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
    If Not LastCell Is Nothing Then
        LastRow = LastCell.Row ' get last Row with data
    End If

    Set r = Worksheets("Sheet1").Range("A1:D" & LastRow) '<-- set Range to "Sheet1"
End With


End Sub

答案 2 :(得分:0)

尝试:

Dim r As Range: Set r = Sheets("Sheet1").Range("A1:D4")