简体   繁体   中英

excel-vba if function message “collection is one-based”

I got the error message "collection is one-based" but I can't figure out what's wrong with my code.

The following table is the dataprovider: dp2 = ActiveDocument.DataProviders("Test2")

     Quantity      Switchmon      Currency
     -------------------------------------
1)     150             Y             EUR
2)     250,006         N             USD
3)     132,4           Y             EUR
4)      24             Y             GBP
5)       1             N             USD

Now I need to send an automated email based on these data. I need a function in Excel-VBA that looks in every row for the value of the column "Switchmon".

When the value is "N", I need to put the character "P" in the email. When the value is "Y", I need to put the value of the column "Currency" there.

The result in my email should look like this:

1) 150  EUR
2) 250,006  P
3) 132,4  EUR
4) 24  GBP
5) 1  P

I tried to achieve this with the following function:

Dim strbody As String
Dim dp1 As DataProvider
Dim dp2 As DataProvider
Set dp2 = ActiveDocument.DataProviders("Test2")
Dim k As Integer
Dim numcurr As String

If dp2.Columns("Switchmon").Item(k) = "N" Then
    numcurr = "P"
Else
    numcurr = dp2.Columns("Currency").Item(k)
End If

For k = 1 To dp2.Columns(1).Count
    strbody = dp2.Columns("Quantity").Item(k) & "numcurr"
    Debug.Print strbody
Next k

This function gives me an error message "collection is one-based". What's wrong with my code?

Note:

I know that I could just add a column in Excel with an if() formula but unfortunately that's not a solution in this particular case.

Above your For loop you use variable k but because you just decalared it as an int and didn't set it, it defaults to 0. Columns.Item() is 1 based (starts with item 1, not 0) so you get an error. Set k before using it.

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