[英]VBA set range for ActiveSheet instead of A1:B2
I'm a noob in VBA I have data range from Row1 to Row 226 , trying to export it as csv file in comma delimited. 我是VBA的菜鸟,我的数据范围是从Row1到第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
I want to set the Range to be the current sheet "Sheet1" 我想将范围设置为当前工作表“ Sheet1”
When I do Dim r As Range: Set r = Range("Sheet1")
, it's throwing out me an error and I can't seem to find what I desire on SO. 当我做
Dim r As Range: Set r = Range("Sheet1")
,它抛出了一个错误,我似乎找不到我想要的东西。
Can anyone please help me? 谁能帮帮我吗? Thank you
谢谢
You need to find the last row and then construct your range. 您需要找到最后一行,然后构造范围。 See This link
看到这个链接
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
and in case your last column is also not fixed then use this 如果您的最后一列也没有固定,请使用此
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
Try the code below, as good practice always use Option Explicit
at the top of your module. 尝试下面的代码,因为好的做法总是在模块顶部使用
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
尝试:
Dim r As Range: Set r = Sheets("Sheet1").Range("A1:D4")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.