选择第一列(A),而不是选择中的第一列(VBA-Excel)

时间:2015-04-14 06:56:05

标签: excel-vba vba excel

我一直试图这样做一段时间,但我很难过。我正在尝试循环选择,以便我可以获取一些信息并放入并保存在文本文件中。它可以工作,除了当选择不在A列中开始时,一些数据不会被带入文本文件(它将Columns(1)作为选择中的第一列)。这是代码:

Sub SaveInfoTxtFile()

Dim oCell As Range
Dim myRange As Range
Dim fso As Object
Dim oFile As Object
Dim LastRow As Long
Dim wholeselect As String

Dim year As String
Dim make As String
Dim model As String

Set myRange = Selection
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
wholeselect = CStr(myRange.Row) & ":" & CStr(LastRow)
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile("C:\SSE\test.txt")

Rows(wholeselect).Select

For Each oCell In myRange

 year = oCell.Columns(1).Text
 make = oCell.Columns(2).Text
 model = oCell.Columns(3).Text

oFile.WriteLine year & " " & make & " " & model
oFile.WriteLine

Next oCell

oFile.WriteLine "Name: Blah"
oFile.WriteLine "Company: Blah2"
oFile.Close
Set fso = Nothing
Set oFile = Nothing

End Sub

建议?

1 个答案:

答案 0 :(得分:0)

以下是解决此问题的两种方法:

year = oCell.EntireRow.Columns(1).Text

恕我直言,最好设置循环的范围,以便整合整行。在循环中执行它效率较低。

set myRange = rows(wholeselect).EntireRow
For Each oCell In myRange
...