Identify Two Different Columns with One FunctionHow do I search for a word in Excel Using VBA and then Delete the entire row?excel replace function in access vbaConditional copy Excel File-2 data to excel file-1?Excel stops responding while executing loopTake the date in one worksheet and find the same date in another worksheet column and return the cell reference for that date to use in a loopInsert line after last row of specific textCopy non-adjacent cells and paste transpose but not to an entire rowDynamic VBA Delete based on cell not containing Part of a textCombined data from multiple sheets into one sheetVBA not working (copy data from one file and paste to different workbook below last row of data)

How to report a triplet of septets in NMR tabulation?

Prevent a directory in /tmp from being deleted

How can I fix this gap between bookcases I made?

My colleague's body is amazing

least quadratic residue under GRH: an EXPLICIT bound

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

Is it possible to make sharp wind that can cut stuff from afar?

When blogging recipes, how can I support both readers who want the narrative/journey and ones who want the printer-friendly recipe?

What do you call a Matrix-like slowdown and camera movement effect?

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

New order #4: World

Why is an old chain unsafe?

How can the DM most effectively choose 1 out of an odd number of players to be targeted by an attack or effect?

What Brexit solution does the DUP want?

Draw simple lines in Inkscape

What do you call something that goes against the spirit of the law, but is legal when interpreting the law to the letter?

Concept of linear mappings are confusing me

Circuitry of TV splitters

Why has Russell's definition of numbers using equivalence classes been finally abandoned? ( If it has actually been abandoned).

Can Medicine checks be used, with decent rolls, to completely mitigate the risk of death from ongoing damage?

The use of multiple foreign keys on same column in SQL Server

Example of a relative pronoun

Copycat chess is back

Is there really no realistic way for a skeleton monster to move around without magic?



Identify Two Different Columns with One Function


How do I search for a word in Excel Using VBA and then Delete the entire row?excel replace function in access vbaConditional copy Excel File-2 data to excel file-1?Excel stops responding while executing loopTake the date in one worksheet and find the same date in another worksheet column and return the cell reference for that date to use in a loopInsert line after last row of specific textCopy non-adjacent cells and paste transpose but not to an entire rowDynamic VBA Delete based on cell not containing Part of a textCombined data from multiple sheets into one sheetVBA not working (copy data from one file and paste to different workbook below last row of data)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















Here is the function that can identify a column by its header:



Function find_Col(header As String) As Range

Dim aCell As Range, rng As Range
Dim col As Long, lRow As Long
Dim colName As String
Dim y As Workbook
Dim ws1 As Worksheet

Set y = Workbooks("Template.xlsm")

Set ws1 = y.Sheets("Results")

With ws1

Set aCell = Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

col = aCell.Column
colName = Split(.Cells(, col).Address, "$")(1)

lRow = Range(colName & .Rows.count).End(xlUp).Row + 1

Set myCol = Range(colName & "2")

'This is your range
Set find_Col = Range(myCol.Address & ":" & colName & lRow)

find_Col.Select

End With

End Function


Then I call the function in the sub:



Sub myCol_Find()

find_Col ("Product")

End Sub


The above works fine, but the problem I am facing is that if the column I am searching for is pretty much blank, excluding the header, then my function will only select the first 2 rows under the header. Also, a second issue, it selects the row just after the last row as well. So if the first row under the heading is B3 and the last row is B10, it selects B3:B11.



As a result of this, I thought that it would perhaps work better by first identifying a column with data in it (which I know will always have data in it) then use this column to find the last row of data, and finally use the actual column I need for selection.



So I first did a test by changing this line:



 lRow = Range(colName & .Rows.count).End(xlUp).Row + 1


To this:



 lRow = Range("A" & .Rows.count).End(xlUp).Row + 1


And this selected all the cells in my searched for column based on the total rows found in Column A.



Then I thought instead of specifically naming a column, I'll apply the same logic of "finding" a column to find "Column A". So I have this:



Function find_Col(header As String) As Range

Dim aCell As Range, rng As Range, def_Header As Range
Dim col As Long, lRow As Long, defCol As Long
Dim colName As String, defColName As String
Dim y As Workbook
Dim ws1 As Worksheet

Set y = Workbooks("Template.xlsm")

Set ws1 = y.Sheets("Results")

With ws1

Set def_Header = Cells.Find(what:="ID", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

defCol = def_Header.Column
defColName = Split(.Cells(, def_Col).Address, "$")(1)

Set aCell = Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

col = aCell.Column
colName = Split(.Cells(, col).Address, "$")(1)

' lRow = Range(colName & .Rows.count).End(xlUp).Row + 1

lRow = Range(defColName & .Rows.count).End(xlUp).Row + 1

Set myCol = Range(colName & "2")

'This is your range
Set find_Col = Range(myCol.Address & ":" & colName & lRow)

find_Col.Select

End With

End Function


Extra code added:



Dim def_Header As Range
Dim defCol As Long
Dim defColName As String

Set def_Header = Cells.Find(what:="KW_ID", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

defCol = def_Header.Column
defColName = Split(.Cells(, defCol).Address, "$")(1)


And changed this:



lRow = Range("A" & .Rows.count).End(xlUp).Row + 1


To this:



lRow = Range(defColName & .Rows.count).End(xlUp).Row + 1


Now, I am getting an error at the line:



defCol = def_Header.Column


Error:




Object variable of With block variable not set




I don't quite know what the problem is as it didn't give me this error previously when I defined aCell.



So currently, I am facing two issues:



  1. Selection is selecting one extra cell than what is needed

  2. I don't know why I am receiving the above error









share|improve this question



















  • 1





    To avoid the extra row just remove the +1 You're not scoping anything inside your With block (ie. you should be prefixing Range etc with .

    – Tim Williams
    Mar 8 at 6:18












  • OMG. ;/ Lo, I feel like a fool. Keep missing these simple issues. Thank you @TimWilliams :)

    – Eitel Dagnin
    Mar 8 at 6:19






  • 1





    def_Header will be Nothing if the header is not found, so you need to check for that.

    – Tim Williams
    Mar 8 at 6:20











  • Ahhh! The header name wasn't updated correctly. Thank you for the help @TimWilliams :)

    – Eitel Dagnin
    Mar 8 at 6:32






  • 1





    As a bonus, you can simply use find_Col("Product").Select in your main code. This way you can avoid using .Select in your function which may have unintended consequences in the future. Actually, you can use any of the Range properties and methods on the function call line because the return of the function is a Range.

    – AJD
    Mar 8 at 6:39

















1















Here is the function that can identify a column by its header:



Function find_Col(header As String) As Range

Dim aCell As Range, rng As Range
Dim col As Long, lRow As Long
Dim colName As String
Dim y As Workbook
Dim ws1 As Worksheet

Set y = Workbooks("Template.xlsm")

Set ws1 = y.Sheets("Results")

With ws1

Set aCell = Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

col = aCell.Column
colName = Split(.Cells(, col).Address, "$")(1)

lRow = Range(colName & .Rows.count).End(xlUp).Row + 1

Set myCol = Range(colName & "2")

'This is your range
Set find_Col = Range(myCol.Address & ":" & colName & lRow)

find_Col.Select

End With

End Function


Then I call the function in the sub:



Sub myCol_Find()

find_Col ("Product")

End Sub


The above works fine, but the problem I am facing is that if the column I am searching for is pretty much blank, excluding the header, then my function will only select the first 2 rows under the header. Also, a second issue, it selects the row just after the last row as well. So if the first row under the heading is B3 and the last row is B10, it selects B3:B11.



As a result of this, I thought that it would perhaps work better by first identifying a column with data in it (which I know will always have data in it) then use this column to find the last row of data, and finally use the actual column I need for selection.



So I first did a test by changing this line:



 lRow = Range(colName & .Rows.count).End(xlUp).Row + 1


To this:



 lRow = Range("A" & .Rows.count).End(xlUp).Row + 1


And this selected all the cells in my searched for column based on the total rows found in Column A.



Then I thought instead of specifically naming a column, I'll apply the same logic of "finding" a column to find "Column A". So I have this:



Function find_Col(header As String) As Range

Dim aCell As Range, rng As Range, def_Header As Range
Dim col As Long, lRow As Long, defCol As Long
Dim colName As String, defColName As String
Dim y As Workbook
Dim ws1 As Worksheet

Set y = Workbooks("Template.xlsm")

Set ws1 = y.Sheets("Results")

With ws1

Set def_Header = Cells.Find(what:="ID", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

defCol = def_Header.Column
defColName = Split(.Cells(, def_Col).Address, "$")(1)

Set aCell = Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

col = aCell.Column
colName = Split(.Cells(, col).Address, "$")(1)

' lRow = Range(colName & .Rows.count).End(xlUp).Row + 1

lRow = Range(defColName & .Rows.count).End(xlUp).Row + 1

Set myCol = Range(colName & "2")

'This is your range
Set find_Col = Range(myCol.Address & ":" & colName & lRow)

find_Col.Select

End With

End Function


Extra code added:



Dim def_Header As Range
Dim defCol As Long
Dim defColName As String

Set def_Header = Cells.Find(what:="KW_ID", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

defCol = def_Header.Column
defColName = Split(.Cells(, defCol).Address, "$")(1)


And changed this:



lRow = Range("A" & .Rows.count).End(xlUp).Row + 1


To this:



lRow = Range(defColName & .Rows.count).End(xlUp).Row + 1


Now, I am getting an error at the line:



defCol = def_Header.Column


Error:




Object variable of With block variable not set




I don't quite know what the problem is as it didn't give me this error previously when I defined aCell.



So currently, I am facing two issues:



  1. Selection is selecting one extra cell than what is needed

  2. I don't know why I am receiving the above error









share|improve this question



















  • 1





    To avoid the extra row just remove the +1 You're not scoping anything inside your With block (ie. you should be prefixing Range etc with .

    – Tim Williams
    Mar 8 at 6:18












  • OMG. ;/ Lo, I feel like a fool. Keep missing these simple issues. Thank you @TimWilliams :)

    – Eitel Dagnin
    Mar 8 at 6:19






  • 1





    def_Header will be Nothing if the header is not found, so you need to check for that.

    – Tim Williams
    Mar 8 at 6:20











  • Ahhh! The header name wasn't updated correctly. Thank you for the help @TimWilliams :)

    – Eitel Dagnin
    Mar 8 at 6:32






  • 1





    As a bonus, you can simply use find_Col("Product").Select in your main code. This way you can avoid using .Select in your function which may have unintended consequences in the future. Actually, you can use any of the Range properties and methods on the function call line because the return of the function is a Range.

    – AJD
    Mar 8 at 6:39













1












1








1








Here is the function that can identify a column by its header:



Function find_Col(header As String) As Range

Dim aCell As Range, rng As Range
Dim col As Long, lRow As Long
Dim colName As String
Dim y As Workbook
Dim ws1 As Worksheet

Set y = Workbooks("Template.xlsm")

Set ws1 = y.Sheets("Results")

With ws1

Set aCell = Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

col = aCell.Column
colName = Split(.Cells(, col).Address, "$")(1)

lRow = Range(colName & .Rows.count).End(xlUp).Row + 1

Set myCol = Range(colName & "2")

'This is your range
Set find_Col = Range(myCol.Address & ":" & colName & lRow)

find_Col.Select

End With

End Function


Then I call the function in the sub:



Sub myCol_Find()

find_Col ("Product")

End Sub


The above works fine, but the problem I am facing is that if the column I am searching for is pretty much blank, excluding the header, then my function will only select the first 2 rows under the header. Also, a second issue, it selects the row just after the last row as well. So if the first row under the heading is B3 and the last row is B10, it selects B3:B11.



As a result of this, I thought that it would perhaps work better by first identifying a column with data in it (which I know will always have data in it) then use this column to find the last row of data, and finally use the actual column I need for selection.



So I first did a test by changing this line:



 lRow = Range(colName & .Rows.count).End(xlUp).Row + 1


To this:



 lRow = Range("A" & .Rows.count).End(xlUp).Row + 1


And this selected all the cells in my searched for column based on the total rows found in Column A.



Then I thought instead of specifically naming a column, I'll apply the same logic of "finding" a column to find "Column A". So I have this:



Function find_Col(header As String) As Range

Dim aCell As Range, rng As Range, def_Header As Range
Dim col As Long, lRow As Long, defCol As Long
Dim colName As String, defColName As String
Dim y As Workbook
Dim ws1 As Worksheet

Set y = Workbooks("Template.xlsm")

Set ws1 = y.Sheets("Results")

With ws1

Set def_Header = Cells.Find(what:="ID", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

defCol = def_Header.Column
defColName = Split(.Cells(, def_Col).Address, "$")(1)

Set aCell = Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

col = aCell.Column
colName = Split(.Cells(, col).Address, "$")(1)

' lRow = Range(colName & .Rows.count).End(xlUp).Row + 1

lRow = Range(defColName & .Rows.count).End(xlUp).Row + 1

Set myCol = Range(colName & "2")

'This is your range
Set find_Col = Range(myCol.Address & ":" & colName & lRow)

find_Col.Select

End With

End Function


Extra code added:



Dim def_Header As Range
Dim defCol As Long
Dim defColName As String

Set def_Header = Cells.Find(what:="KW_ID", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

defCol = def_Header.Column
defColName = Split(.Cells(, defCol).Address, "$")(1)


And changed this:



lRow = Range("A" & .Rows.count).End(xlUp).Row + 1


To this:



lRow = Range(defColName & .Rows.count).End(xlUp).Row + 1


Now, I am getting an error at the line:



defCol = def_Header.Column


Error:




Object variable of With block variable not set




I don't quite know what the problem is as it didn't give me this error previously when I defined aCell.



So currently, I am facing two issues:



  1. Selection is selecting one extra cell than what is needed

  2. I don't know why I am receiving the above error









share|improve this question
















Here is the function that can identify a column by its header:



Function find_Col(header As String) As Range

Dim aCell As Range, rng As Range
Dim col As Long, lRow As Long
Dim colName As String
Dim y As Workbook
Dim ws1 As Worksheet

Set y = Workbooks("Template.xlsm")

Set ws1 = y.Sheets("Results")

With ws1

Set aCell = Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

col = aCell.Column
colName = Split(.Cells(, col).Address, "$")(1)

lRow = Range(colName & .Rows.count).End(xlUp).Row + 1

Set myCol = Range(colName & "2")

'This is your range
Set find_Col = Range(myCol.Address & ":" & colName & lRow)

find_Col.Select

End With

End Function


Then I call the function in the sub:



Sub myCol_Find()

find_Col ("Product")

End Sub


The above works fine, but the problem I am facing is that if the column I am searching for is pretty much blank, excluding the header, then my function will only select the first 2 rows under the header. Also, a second issue, it selects the row just after the last row as well. So if the first row under the heading is B3 and the last row is B10, it selects B3:B11.



As a result of this, I thought that it would perhaps work better by first identifying a column with data in it (which I know will always have data in it) then use this column to find the last row of data, and finally use the actual column I need for selection.



So I first did a test by changing this line:



 lRow = Range(colName & .Rows.count).End(xlUp).Row + 1


To this:



 lRow = Range("A" & .Rows.count).End(xlUp).Row + 1


And this selected all the cells in my searched for column based on the total rows found in Column A.



Then I thought instead of specifically naming a column, I'll apply the same logic of "finding" a column to find "Column A". So I have this:



Function find_Col(header As String) As Range

Dim aCell As Range, rng As Range, def_Header As Range
Dim col As Long, lRow As Long, defCol As Long
Dim colName As String, defColName As String
Dim y As Workbook
Dim ws1 As Worksheet

Set y = Workbooks("Template.xlsm")

Set ws1 = y.Sheets("Results")

With ws1

Set def_Header = Cells.Find(what:="ID", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

defCol = def_Header.Column
defColName = Split(.Cells(, def_Col).Address, "$")(1)

Set aCell = Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

col = aCell.Column
colName = Split(.Cells(, col).Address, "$")(1)

' lRow = Range(colName & .Rows.count).End(xlUp).Row + 1

lRow = Range(defColName & .Rows.count).End(xlUp).Row + 1

Set myCol = Range(colName & "2")

'This is your range
Set find_Col = Range(myCol.Address & ":" & colName & lRow)

find_Col.Select

End With

End Function


Extra code added:



Dim def_Header As Range
Dim defCol As Long
Dim defColName As String

Set def_Header = Cells.Find(what:="KW_ID", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)

defCol = def_Header.Column
defColName = Split(.Cells(, defCol).Address, "$")(1)


And changed this:



lRow = Range("A" & .Rows.count).End(xlUp).Row + 1


To this:



lRow = Range(defColName & .Rows.count).End(xlUp).Row + 1


Now, I am getting an error at the line:



defCol = def_Header.Column


Error:




Object variable of With block variable not set




I don't quite know what the problem is as it didn't give me this error previously when I defined aCell.



So currently, I am facing two issues:



  1. Selection is selecting one extra cell than what is needed

  2. I don't know why I am receiving the above error






excel vba






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 9:20









Pᴇʜ

25.1k63052




25.1k63052










asked Mar 8 at 6:03









Eitel DagninEitel Dagnin

362415




362415







  • 1





    To avoid the extra row just remove the +1 You're not scoping anything inside your With block (ie. you should be prefixing Range etc with .

    – Tim Williams
    Mar 8 at 6:18












  • OMG. ;/ Lo, I feel like a fool. Keep missing these simple issues. Thank you @TimWilliams :)

    – Eitel Dagnin
    Mar 8 at 6:19






  • 1





    def_Header will be Nothing if the header is not found, so you need to check for that.

    – Tim Williams
    Mar 8 at 6:20











  • Ahhh! The header name wasn't updated correctly. Thank you for the help @TimWilliams :)

    – Eitel Dagnin
    Mar 8 at 6:32






  • 1





    As a bonus, you can simply use find_Col("Product").Select in your main code. This way you can avoid using .Select in your function which may have unintended consequences in the future. Actually, you can use any of the Range properties and methods on the function call line because the return of the function is a Range.

    – AJD
    Mar 8 at 6:39












  • 1





    To avoid the extra row just remove the +1 You're not scoping anything inside your With block (ie. you should be prefixing Range etc with .

    – Tim Williams
    Mar 8 at 6:18












  • OMG. ;/ Lo, I feel like a fool. Keep missing these simple issues. Thank you @TimWilliams :)

    – Eitel Dagnin
    Mar 8 at 6:19






  • 1





    def_Header will be Nothing if the header is not found, so you need to check for that.

    – Tim Williams
    Mar 8 at 6:20











  • Ahhh! The header name wasn't updated correctly. Thank you for the help @TimWilliams :)

    – Eitel Dagnin
    Mar 8 at 6:32






  • 1





    As a bonus, you can simply use find_Col("Product").Select in your main code. This way you can avoid using .Select in your function which may have unintended consequences in the future. Actually, you can use any of the Range properties and methods on the function call line because the return of the function is a Range.

    – AJD
    Mar 8 at 6:39







1




1





To avoid the extra row just remove the +1 You're not scoping anything inside your With block (ie. you should be prefixing Range etc with .

– Tim Williams
Mar 8 at 6:18






To avoid the extra row just remove the +1 You're not scoping anything inside your With block (ie. you should be prefixing Range etc with .

– Tim Williams
Mar 8 at 6:18














OMG. ;/ Lo, I feel like a fool. Keep missing these simple issues. Thank you @TimWilliams :)

– Eitel Dagnin
Mar 8 at 6:19





OMG. ;/ Lo, I feel like a fool. Keep missing these simple issues. Thank you @TimWilliams :)

– Eitel Dagnin
Mar 8 at 6:19




1




1





def_Header will be Nothing if the header is not found, so you need to check for that.

– Tim Williams
Mar 8 at 6:20





def_Header will be Nothing if the header is not found, so you need to check for that.

– Tim Williams
Mar 8 at 6:20













Ahhh! The header name wasn't updated correctly. Thank you for the help @TimWilliams :)

– Eitel Dagnin
Mar 8 at 6:32





Ahhh! The header name wasn't updated correctly. Thank you for the help @TimWilliams :)

– Eitel Dagnin
Mar 8 at 6:32




1




1





As a bonus, you can simply use find_Col("Product").Select in your main code. This way you can avoid using .Select in your function which may have unintended consequences in the future. Actually, you can use any of the Range properties and methods on the function call line because the return of the function is a Range.

– AJD
Mar 8 at 6:39





As a bonus, you can simply use find_Col("Product").Select in your main code. This way you can avoid using .Select in your function which may have unintended consequences in the future. Actually, you can use any of the Range properties and methods on the function call line because the return of the function is a Range.

– AJD
Mar 8 at 6:39












1 Answer
1






active

oldest

votes


















2














This should work:



EDIT: updated to deal with cases where the header is found but there is no data



Function find_Col(header As String) As Range

Dim aCell As Range, bCell As Range, rng As Range

With Workbooks("Template.xlsm").Sheets("Results")

Set aCell = .Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, _
MatchCase:=False, SearchFormat:=False)

If Not aCell Is Nothing Then
Set aCell = aCell.Offset(1, 0)
Set bCell = .Cells(.Rows.Count, aCell.Column).End(xlUp)
If bCell.Row > aCell.Row Then
Set rng = .Range(aCell, bCell) 'column has some content
Else
Set rng = aCell 'or nothing? 'column has no content...
End If
End If
End With

Set find_col = rng
End Function





share|improve this answer

























  • Works great. Thank you :)

    – Eitel Dagnin
    Mar 8 at 6:48






  • 3





    ++ @EitelDagnin: You will still have to do one extra check.. If Not find_Col("Product") Is nothing Then That is because if the header is not found then Set find_col = rng will equate to Set find_col = Nothing and you will get that error again..

    – Siddharth Rout
    Mar 8 at 6:55











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55057582%2fidentify-two-different-columns-with-one-function%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














This should work:



EDIT: updated to deal with cases where the header is found but there is no data



Function find_Col(header As String) As Range

Dim aCell As Range, bCell As Range, rng As Range

With Workbooks("Template.xlsm").Sheets("Results")

Set aCell = .Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, _
MatchCase:=False, SearchFormat:=False)

If Not aCell Is Nothing Then
Set aCell = aCell.Offset(1, 0)
Set bCell = .Cells(.Rows.Count, aCell.Column).End(xlUp)
If bCell.Row > aCell.Row Then
Set rng = .Range(aCell, bCell) 'column has some content
Else
Set rng = aCell 'or nothing? 'column has no content...
End If
End If
End With

Set find_col = rng
End Function





share|improve this answer

























  • Works great. Thank you :)

    – Eitel Dagnin
    Mar 8 at 6:48






  • 3





    ++ @EitelDagnin: You will still have to do one extra check.. If Not find_Col("Product") Is nothing Then That is because if the header is not found then Set find_col = rng will equate to Set find_col = Nothing and you will get that error again..

    – Siddharth Rout
    Mar 8 at 6:55















2














This should work:



EDIT: updated to deal with cases where the header is found but there is no data



Function find_Col(header As String) As Range

Dim aCell As Range, bCell As Range, rng As Range

With Workbooks("Template.xlsm").Sheets("Results")

Set aCell = .Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, _
MatchCase:=False, SearchFormat:=False)

If Not aCell Is Nothing Then
Set aCell = aCell.Offset(1, 0)
Set bCell = .Cells(.Rows.Count, aCell.Column).End(xlUp)
If bCell.Row > aCell.Row Then
Set rng = .Range(aCell, bCell) 'column has some content
Else
Set rng = aCell 'or nothing? 'column has no content...
End If
End If
End With

Set find_col = rng
End Function





share|improve this answer

























  • Works great. Thank you :)

    – Eitel Dagnin
    Mar 8 at 6:48






  • 3





    ++ @EitelDagnin: You will still have to do one extra check.. If Not find_Col("Product") Is nothing Then That is because if the header is not found then Set find_col = rng will equate to Set find_col = Nothing and you will get that error again..

    – Siddharth Rout
    Mar 8 at 6:55













2












2








2







This should work:



EDIT: updated to deal with cases where the header is found but there is no data



Function find_Col(header As String) As Range

Dim aCell As Range, bCell As Range, rng As Range

With Workbooks("Template.xlsm").Sheets("Results")

Set aCell = .Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, _
MatchCase:=False, SearchFormat:=False)

If Not aCell Is Nothing Then
Set aCell = aCell.Offset(1, 0)
Set bCell = .Cells(.Rows.Count, aCell.Column).End(xlUp)
If bCell.Row > aCell.Row Then
Set rng = .Range(aCell, bCell) 'column has some content
Else
Set rng = aCell 'or nothing? 'column has no content...
End If
End If
End With

Set find_col = rng
End Function





share|improve this answer















This should work:



EDIT: updated to deal with cases where the header is found but there is no data



Function find_Col(header As String) As Range

Dim aCell As Range, bCell As Range, rng As Range

With Workbooks("Template.xlsm").Sheets("Results")

Set aCell = .Cells.Find(what:=header, LookIn:=xlValues, lookat:=xlWhole, _
MatchCase:=False, SearchFormat:=False)

If Not aCell Is Nothing Then
Set aCell = aCell.Offset(1, 0)
Set bCell = .Cells(.Rows.Count, aCell.Column).End(xlUp)
If bCell.Row > aCell.Row Then
Set rng = .Range(aCell, bCell) 'column has some content
Else
Set rng = aCell 'or nothing? 'column has no content...
End If
End If
End With

Set find_col = rng
End Function






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 8 at 18:50

























answered Mar 8 at 6:38









Tim WilliamsTim Williams

89.3k97087




89.3k97087












  • Works great. Thank you :)

    – Eitel Dagnin
    Mar 8 at 6:48






  • 3





    ++ @EitelDagnin: You will still have to do one extra check.. If Not find_Col("Product") Is nothing Then That is because if the header is not found then Set find_col = rng will equate to Set find_col = Nothing and you will get that error again..

    – Siddharth Rout
    Mar 8 at 6:55

















  • Works great. Thank you :)

    – Eitel Dagnin
    Mar 8 at 6:48






  • 3





    ++ @EitelDagnin: You will still have to do one extra check.. If Not find_Col("Product") Is nothing Then That is because if the header is not found then Set find_col = rng will equate to Set find_col = Nothing and you will get that error again..

    – Siddharth Rout
    Mar 8 at 6:55
















Works great. Thank you :)

– Eitel Dagnin
Mar 8 at 6:48





Works great. Thank you :)

– Eitel Dagnin
Mar 8 at 6:48




3




3





++ @EitelDagnin: You will still have to do one extra check.. If Not find_Col("Product") Is nothing Then That is because if the header is not found then Set find_col = rng will equate to Set find_col = Nothing and you will get that error again..

– Siddharth Rout
Mar 8 at 6:55





++ @EitelDagnin: You will still have to do one extra check.. If Not find_Col("Product") Is nothing Then That is because if the header is not found then Set find_col = rng will equate to Set find_col = Nothing and you will get that error again..

– Siddharth Rout
Mar 8 at 6:55



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55057582%2fidentify-two-different-columns-with-one-function%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved