简体   繁体   中英

Selecting the first column (A), not the first in a selection (VBA-Excel)

I've been trying to do this for a while but I'm stumped. I'm trying to loop through a selection so that I can take some information and put and save on a text file. It works, except that when the selection does NOT start in Column A, some data is not brought into the text file (it takes Columns(1) as the first column in the selection). Here's the code:

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

Suggestions?

Here are 2 ways to solve this:

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

IMHO it would be better to set the range over which you loop so that the entire row is incorporated. Doing it within the loop is less efficient.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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