WorksheetFunction.Match as array with variable range
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I am trying to implement a .Match function as array with a variable range in VBA, to find the first non-zero cell in a specific range.
However, currently I only receive a runtime error 1004.
Any help is much appreciated! Thanks
Set myRange = Worksheets("Portf_Mod").Range("AB368:CY368")
With Application.WorksheetFunction
Date_col = .Match(True, [myRange <> 0], 0)
End With
excel vba excel-vba worksheet-function
add a comment |
I am trying to implement a .Match function as array with a variable range in VBA, to find the first non-zero cell in a specific range.
However, currently I only receive a runtime error 1004.
Any help is much appreciated! Thanks
Set myRange = Worksheets("Portf_Mod").Range("AB368:CY368")
With Application.WorksheetFunction
Date_col = .Match(True, [myRange <> 0], 0)
End With
excel vba excel-vba worksheet-function
Take a look here, you could probably adjust this answer to fit your needs
– Jchang43
Nov 23 '18 at 16:52
I think the problem came from your =MATCH utilisation. You use it on multiple column. If you try the same on a formula you will have a "#NA" error.
– BenderIO
Nov 23 '18 at 16:54
add a comment |
I am trying to implement a .Match function as array with a variable range in VBA, to find the first non-zero cell in a specific range.
However, currently I only receive a runtime error 1004.
Any help is much appreciated! Thanks
Set myRange = Worksheets("Portf_Mod").Range("AB368:CY368")
With Application.WorksheetFunction
Date_col = .Match(True, [myRange <> 0], 0)
End With
excel vba excel-vba worksheet-function
I am trying to implement a .Match function as array with a variable range in VBA, to find the first non-zero cell in a specific range.
However, currently I only receive a runtime error 1004.
Any help is much appreciated! Thanks
Set myRange = Worksheets("Portf_Mod").Range("AB368:CY368")
With Application.WorksheetFunction
Date_col = .Match(True, [myRange <> 0], 0)
End With
excel vba excel-vba worksheet-function
excel vba excel-vba worksheet-function
edited Nov 26 '18 at 7:28
Pᴇʜ
25.3k63052
25.3k63052
asked Nov 23 '18 at 16:38
Tobi1990Tobi1990
405
405
Take a look here, you could probably adjust this answer to fit your needs
– Jchang43
Nov 23 '18 at 16:52
I think the problem came from your =MATCH utilisation. You use it on multiple column. If you try the same on a formula you will have a "#NA" error.
– BenderIO
Nov 23 '18 at 16:54
add a comment |
Take a look here, you could probably adjust this answer to fit your needs
– Jchang43
Nov 23 '18 at 16:52
I think the problem came from your =MATCH utilisation. You use it on multiple column. If you try the same on a formula you will have a "#NA" error.
– BenderIO
Nov 23 '18 at 16:54
Take a look here, you could probably adjust this answer to fit your needs
– Jchang43
Nov 23 '18 at 16:52
Take a look here, you could probably adjust this answer to fit your needs
– Jchang43
Nov 23 '18 at 16:52
I think the problem came from your =MATCH utilisation. You use it on multiple column. If you try the same on a formula you will have a "#NA" error.
– BenderIO
Nov 23 '18 at 16:54
I think the problem came from your =MATCH utilisation. You use it on multiple column. If you try the same on a formula you will have a "#NA" error.
– BenderIO
Nov 23 '18 at 16:54
add a comment |
4 Answers
4
active
oldest
votes
As you are using VBA, instead of using Match
you could use the API to make for a more explicit and maintainable code:
Function FirstNonZeroCell(rng As Range) As Range
Dim cell As Range
For Each cell In rng.Cells
If cell.Value <> 0 Then
Set FirstNonZeroCell = cell
Exit Function
End If
Next
End Function
Or if you want a more compact version (but less readable in my opinion):
Function FirstNonZeroCell(rng As Range) As Range
For Each FirstNonZeroCell In rng.Cells
If FirstNonZeroCell.Value <> 0 Then Exit Function
Next
Set FirstNonZeroCell = Nothing
End Function
Here is a sample of use:
Sub test()
Dim res As Range
Set res = FirstNonZeroCell(Range("A1:Z100"))
If Not res Is Nothing Then
MsgBox "Found value " & res.Value & " in cell " & res.Address & "."
Else
MsgBox "No match has been found!"
End If
End Sub
add a comment |
Think the array element is throwing out your approach so here is an alternative.
It's not clear if you want the first non-zero value or its position so this covers both.
Date_col = Evaluate("MATCH(TRUE," & myRange.Address & "<>0,0)") 'returns position
Date_col = Evaluate("INDEX(" & myRange.Address & ",MATCH(TRUE," & myRange.Address & "<>0,0))") 'returns value
This works perfectly! Thanks
– Tobi1990
Nov 23 '18 at 17:25
add a comment |
It's the first time I came across an "array formula" in VBA. This is not wrong, but not very evident to understand/troubleshoot. On my machine [where the range had all empty cells, it gives an error [myRange <> 0] = Error 2092
, then within the Match function, then gets another error...
The array formulas are great in a formula worksheet only, but I feel you should avoid them in VBA. You have the ability to use loops in VBA, so, don't hesitate to use them! Having your train of though as explicit as possible is key when writing software (so you will understand it later!).
My suggestion would be this :
Option Explicit
Function FindDateColumnInRange(ByVal RangeToLookIn As Range) As Long
If RangeToLookIn.Rows.Count <> 1 Then
'The range you're looking in has more than one row
'what should you do in this case? Look only in the first row?
Else
Dim i As Long
'The range has only one row
For i = 0 To RangeToLookIn.Columns.Count - 1
If RangeToLookIn.Item(1, i).Value <> 0 Then
'should you verifiy that the value is a date value?
FindDateColumnInRange = RangeToLookIn.Item(1, i).Column
Exit Function
End If
Next
End If
'the range didn't have a value different from 0
FindDateColumnInRange = 0
End Function
In action, you would get :
Sub Test()
Dim MyRange As Range
Set MyRange = Worksheets("Portf_Mod").Range("AB368:CY368")
Dim date_col As Integer
date_col = FindDateColumnInRange(MyRange)
If date_col = 0 Then
'There was no date in your range
End If
End Sub
Yeah, it's a lot more long than SJR suggestions, but, it covers every exceptions and you can control how to look if you were to pass a multidimensionnal array (iterate through rows first then columns, or the other way around).
add a comment |
I wouldn't use the Match function for this...
Set myRange = Worksheets("Portf_Mod").Range("AB368:CY368")
On Error Resume Next
Date_col = myRange.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns).Column
On Error GoTo 0
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%2f53450262%2fworksheetfunction-match-as-array-with-variable-range%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
As you are using VBA, instead of using Match
you could use the API to make for a more explicit and maintainable code:
Function FirstNonZeroCell(rng As Range) As Range
Dim cell As Range
For Each cell In rng.Cells
If cell.Value <> 0 Then
Set FirstNonZeroCell = cell
Exit Function
End If
Next
End Function
Or if you want a more compact version (but less readable in my opinion):
Function FirstNonZeroCell(rng As Range) As Range
For Each FirstNonZeroCell In rng.Cells
If FirstNonZeroCell.Value <> 0 Then Exit Function
Next
Set FirstNonZeroCell = Nothing
End Function
Here is a sample of use:
Sub test()
Dim res As Range
Set res = FirstNonZeroCell(Range("A1:Z100"))
If Not res Is Nothing Then
MsgBox "Found value " & res.Value & " in cell " & res.Address & "."
Else
MsgBox "No match has been found!"
End If
End Sub
add a comment |
As you are using VBA, instead of using Match
you could use the API to make for a more explicit and maintainable code:
Function FirstNonZeroCell(rng As Range) As Range
Dim cell As Range
For Each cell In rng.Cells
If cell.Value <> 0 Then
Set FirstNonZeroCell = cell
Exit Function
End If
Next
End Function
Or if you want a more compact version (but less readable in my opinion):
Function FirstNonZeroCell(rng As Range) As Range
For Each FirstNonZeroCell In rng.Cells
If FirstNonZeroCell.Value <> 0 Then Exit Function
Next
Set FirstNonZeroCell = Nothing
End Function
Here is a sample of use:
Sub test()
Dim res As Range
Set res = FirstNonZeroCell(Range("A1:Z100"))
If Not res Is Nothing Then
MsgBox "Found value " & res.Value & " in cell " & res.Address & "."
Else
MsgBox "No match has been found!"
End If
End Sub
add a comment |
As you are using VBA, instead of using Match
you could use the API to make for a more explicit and maintainable code:
Function FirstNonZeroCell(rng As Range) As Range
Dim cell As Range
For Each cell In rng.Cells
If cell.Value <> 0 Then
Set FirstNonZeroCell = cell
Exit Function
End If
Next
End Function
Or if you want a more compact version (but less readable in my opinion):
Function FirstNonZeroCell(rng As Range) As Range
For Each FirstNonZeroCell In rng.Cells
If FirstNonZeroCell.Value <> 0 Then Exit Function
Next
Set FirstNonZeroCell = Nothing
End Function
Here is a sample of use:
Sub test()
Dim res As Range
Set res = FirstNonZeroCell(Range("A1:Z100"))
If Not res Is Nothing Then
MsgBox "Found value " & res.Value & " in cell " & res.Address & "."
Else
MsgBox "No match has been found!"
End If
End Sub
As you are using VBA, instead of using Match
you could use the API to make for a more explicit and maintainable code:
Function FirstNonZeroCell(rng As Range) As Range
Dim cell As Range
For Each cell In rng.Cells
If cell.Value <> 0 Then
Set FirstNonZeroCell = cell
Exit Function
End If
Next
End Function
Or if you want a more compact version (but less readable in my opinion):
Function FirstNonZeroCell(rng As Range) As Range
For Each FirstNonZeroCell In rng.Cells
If FirstNonZeroCell.Value <> 0 Then Exit Function
Next
Set FirstNonZeroCell = Nothing
End Function
Here is a sample of use:
Sub test()
Dim res As Range
Set res = FirstNonZeroCell(Range("A1:Z100"))
If Not res Is Nothing Then
MsgBox "Found value " & res.Value & " in cell " & res.Address & "."
Else
MsgBox "No match has been found!"
End If
End Sub
answered Nov 23 '18 at 17:18
PragmateekPragmateek
9,39695591
9,39695591
add a comment |
add a comment |
Think the array element is throwing out your approach so here is an alternative.
It's not clear if you want the first non-zero value or its position so this covers both.
Date_col = Evaluate("MATCH(TRUE," & myRange.Address & "<>0,0)") 'returns position
Date_col = Evaluate("INDEX(" & myRange.Address & ",MATCH(TRUE," & myRange.Address & "<>0,0))") 'returns value
This works perfectly! Thanks
– Tobi1990
Nov 23 '18 at 17:25
add a comment |
Think the array element is throwing out your approach so here is an alternative.
It's not clear if you want the first non-zero value or its position so this covers both.
Date_col = Evaluate("MATCH(TRUE," & myRange.Address & "<>0,0)") 'returns position
Date_col = Evaluate("INDEX(" & myRange.Address & ",MATCH(TRUE," & myRange.Address & "<>0,0))") 'returns value
This works perfectly! Thanks
– Tobi1990
Nov 23 '18 at 17:25
add a comment |
Think the array element is throwing out your approach so here is an alternative.
It's not clear if you want the first non-zero value or its position so this covers both.
Date_col = Evaluate("MATCH(TRUE," & myRange.Address & "<>0,0)") 'returns position
Date_col = Evaluate("INDEX(" & myRange.Address & ",MATCH(TRUE," & myRange.Address & "<>0,0))") 'returns value
Think the array element is throwing out your approach so here is an alternative.
It's not clear if you want the first non-zero value or its position so this covers both.
Date_col = Evaluate("MATCH(TRUE," & myRange.Address & "<>0,0)") 'returns position
Date_col = Evaluate("INDEX(" & myRange.Address & ",MATCH(TRUE," & myRange.Address & "<>0,0))") 'returns value
edited Nov 23 '18 at 17:07
answered Nov 23 '18 at 17:02
SJRSJR
13.8k31219
13.8k31219
This works perfectly! Thanks
– Tobi1990
Nov 23 '18 at 17:25
add a comment |
This works perfectly! Thanks
– Tobi1990
Nov 23 '18 at 17:25
This works perfectly! Thanks
– Tobi1990
Nov 23 '18 at 17:25
This works perfectly! Thanks
– Tobi1990
Nov 23 '18 at 17:25
add a comment |
It's the first time I came across an "array formula" in VBA. This is not wrong, but not very evident to understand/troubleshoot. On my machine [where the range had all empty cells, it gives an error [myRange <> 0] = Error 2092
, then within the Match function, then gets another error...
The array formulas are great in a formula worksheet only, but I feel you should avoid them in VBA. You have the ability to use loops in VBA, so, don't hesitate to use them! Having your train of though as explicit as possible is key when writing software (so you will understand it later!).
My suggestion would be this :
Option Explicit
Function FindDateColumnInRange(ByVal RangeToLookIn As Range) As Long
If RangeToLookIn.Rows.Count <> 1 Then
'The range you're looking in has more than one row
'what should you do in this case? Look only in the first row?
Else
Dim i As Long
'The range has only one row
For i = 0 To RangeToLookIn.Columns.Count - 1
If RangeToLookIn.Item(1, i).Value <> 0 Then
'should you verifiy that the value is a date value?
FindDateColumnInRange = RangeToLookIn.Item(1, i).Column
Exit Function
End If
Next
End If
'the range didn't have a value different from 0
FindDateColumnInRange = 0
End Function
In action, you would get :
Sub Test()
Dim MyRange As Range
Set MyRange = Worksheets("Portf_Mod").Range("AB368:CY368")
Dim date_col As Integer
date_col = FindDateColumnInRange(MyRange)
If date_col = 0 Then
'There was no date in your range
End If
End Sub
Yeah, it's a lot more long than SJR suggestions, but, it covers every exceptions and you can control how to look if you were to pass a multidimensionnal array (iterate through rows first then columns, or the other way around).
add a comment |
It's the first time I came across an "array formula" in VBA. This is not wrong, but not very evident to understand/troubleshoot. On my machine [where the range had all empty cells, it gives an error [myRange <> 0] = Error 2092
, then within the Match function, then gets another error...
The array formulas are great in a formula worksheet only, but I feel you should avoid them in VBA. You have the ability to use loops in VBA, so, don't hesitate to use them! Having your train of though as explicit as possible is key when writing software (so you will understand it later!).
My suggestion would be this :
Option Explicit
Function FindDateColumnInRange(ByVal RangeToLookIn As Range) As Long
If RangeToLookIn.Rows.Count <> 1 Then
'The range you're looking in has more than one row
'what should you do in this case? Look only in the first row?
Else
Dim i As Long
'The range has only one row
For i = 0 To RangeToLookIn.Columns.Count - 1
If RangeToLookIn.Item(1, i).Value <> 0 Then
'should you verifiy that the value is a date value?
FindDateColumnInRange = RangeToLookIn.Item(1, i).Column
Exit Function
End If
Next
End If
'the range didn't have a value different from 0
FindDateColumnInRange = 0
End Function
In action, you would get :
Sub Test()
Dim MyRange As Range
Set MyRange = Worksheets("Portf_Mod").Range("AB368:CY368")
Dim date_col As Integer
date_col = FindDateColumnInRange(MyRange)
If date_col = 0 Then
'There was no date in your range
End If
End Sub
Yeah, it's a lot more long than SJR suggestions, but, it covers every exceptions and you can control how to look if you were to pass a multidimensionnal array (iterate through rows first then columns, or the other way around).
add a comment |
It's the first time I came across an "array formula" in VBA. This is not wrong, but not very evident to understand/troubleshoot. On my machine [where the range had all empty cells, it gives an error [myRange <> 0] = Error 2092
, then within the Match function, then gets another error...
The array formulas are great in a formula worksheet only, but I feel you should avoid them in VBA. You have the ability to use loops in VBA, so, don't hesitate to use them! Having your train of though as explicit as possible is key when writing software (so you will understand it later!).
My suggestion would be this :
Option Explicit
Function FindDateColumnInRange(ByVal RangeToLookIn As Range) As Long
If RangeToLookIn.Rows.Count <> 1 Then
'The range you're looking in has more than one row
'what should you do in this case? Look only in the first row?
Else
Dim i As Long
'The range has only one row
For i = 0 To RangeToLookIn.Columns.Count - 1
If RangeToLookIn.Item(1, i).Value <> 0 Then
'should you verifiy that the value is a date value?
FindDateColumnInRange = RangeToLookIn.Item(1, i).Column
Exit Function
End If
Next
End If
'the range didn't have a value different from 0
FindDateColumnInRange = 0
End Function
In action, you would get :
Sub Test()
Dim MyRange As Range
Set MyRange = Worksheets("Portf_Mod").Range("AB368:CY368")
Dim date_col As Integer
date_col = FindDateColumnInRange(MyRange)
If date_col = 0 Then
'There was no date in your range
End If
End Sub
Yeah, it's a lot more long than SJR suggestions, but, it covers every exceptions and you can control how to look if you were to pass a multidimensionnal array (iterate through rows first then columns, or the other way around).
It's the first time I came across an "array formula" in VBA. This is not wrong, but not very evident to understand/troubleshoot. On my machine [where the range had all empty cells, it gives an error [myRange <> 0] = Error 2092
, then within the Match function, then gets another error...
The array formulas are great in a formula worksheet only, but I feel you should avoid them in VBA. You have the ability to use loops in VBA, so, don't hesitate to use them! Having your train of though as explicit as possible is key when writing software (so you will understand it later!).
My suggestion would be this :
Option Explicit
Function FindDateColumnInRange(ByVal RangeToLookIn As Range) As Long
If RangeToLookIn.Rows.Count <> 1 Then
'The range you're looking in has more than one row
'what should you do in this case? Look only in the first row?
Else
Dim i As Long
'The range has only one row
For i = 0 To RangeToLookIn.Columns.Count - 1
If RangeToLookIn.Item(1, i).Value <> 0 Then
'should you verifiy that the value is a date value?
FindDateColumnInRange = RangeToLookIn.Item(1, i).Column
Exit Function
End If
Next
End If
'the range didn't have a value different from 0
FindDateColumnInRange = 0
End Function
In action, you would get :
Sub Test()
Dim MyRange As Range
Set MyRange = Worksheets("Portf_Mod").Range("AB368:CY368")
Dim date_col As Integer
date_col = FindDateColumnInRange(MyRange)
If date_col = 0 Then
'There was no date in your range
End If
End Sub
Yeah, it's a lot more long than SJR suggestions, but, it covers every exceptions and you can control how to look if you were to pass a multidimensionnal array (iterate through rows first then columns, or the other way around).
answered Nov 23 '18 at 17:46
CharlesPLCharlesPL
1969
1969
add a comment |
add a comment |
I wouldn't use the Match function for this...
Set myRange = Worksheets("Portf_Mod").Range("AB368:CY368")
On Error Resume Next
Date_col = myRange.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns).Column
On Error GoTo 0
add a comment |
I wouldn't use the Match function for this...
Set myRange = Worksheets("Portf_Mod").Range("AB368:CY368")
On Error Resume Next
Date_col = myRange.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns).Column
On Error GoTo 0
add a comment |
I wouldn't use the Match function for this...
Set myRange = Worksheets("Portf_Mod").Range("AB368:CY368")
On Error Resume Next
Date_col = myRange.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns).Column
On Error GoTo 0
I wouldn't use the Match function for this...
Set myRange = Worksheets("Portf_Mod").Range("AB368:CY368")
On Error Resume Next
Date_col = myRange.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns).Column
On Error GoTo 0
edited Nov 25 '18 at 1:44
answered Nov 23 '18 at 17:37
TragamorTragamor
1,76931024
1,76931024
add a comment |
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%2f53450262%2fworksheetfunction-match-as-array-with-variable-range%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
Take a look here, you could probably adjust this answer to fit your needs
– Jchang43
Nov 23 '18 at 16:52
I think the problem came from your =MATCH utilisation. You use it on multiple column. If you try the same on a formula you will have a "#NA" error.
– BenderIO
Nov 23 '18 at 16:54