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;
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:
- Selection is selecting one extra cell than what is needed
- I don't know why I am receiving the above error
excel vba
|
show 1 more comment
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:
- Selection is selecting one extra cell than what is needed
- I don't know why I am receiving the above error
excel vba
1
To avoid the extra row just remove the+1
You're not scoping anything inside yourWith
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 beNothing
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 usefind_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
|
show 1 more comment
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:
- Selection is selecting one extra cell than what is needed
- I don't know why I am receiving the above error
excel vba
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:
- Selection is selecting one extra cell than what is needed
- I don't know why I am receiving the above error
excel vba
excel vba
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 yourWith
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 beNothing
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 usefind_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
|
show 1 more comment
1
To avoid the extra row just remove the+1
You're not scoping anything inside yourWith
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 beNothing
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 usefind_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
|
show 1 more comment
1 Answer
1
active
oldest
votes
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
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 thenSet find_col = rng
will equate toSet find_col = Nothing
and you will get that error again..
– Siddharth Rout
Mar 8 at 6:55
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
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 thenSet find_col = rng
will equate toSet find_col = Nothing
and you will get that error again..
– Siddharth Rout
Mar 8 at 6:55
add a comment |
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
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 thenSet find_col = rng
will equate toSet find_col = Nothing
and you will get that error again..
– Siddharth Rout
Mar 8 at 6:55
add a comment |
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
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
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 thenSet find_col = rng
will equate toSet find_col = Nothing
and you will get that error again..
– Siddharth Rout
Mar 8 at 6:55
add a comment |
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 thenSet find_col = rng
will equate toSet 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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
1
To avoid the extra row just remove the
+1
You're not scoping anything inside yourWith
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 beNothing
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