0

I am running into an error when writing these multiple 'case when' statements in Excel VBA. The scripting runs perfectly in SQL Server, but I am having trouble formatting it correctly in Excel VBA so that it can run correctly. Please help?!

6
  • 3
    How exactly did you try this in VBA? Please edit your question. Commented Jun 10, 2020 at 13:58
  • 1
    Instead, try creating a Tally table and joining on it. Who would really write a case statement like that. Commented Jun 10, 2020 at 14:03
  • And BTW, if all you are bothered is how to write that in VBA, then try writing it as multiple strings no longer than 255 characters and concatenate. ie: dim sql as string = "select" & _ " case when ..." & _ " when ...". Commented Jun 10, 2020 at 14:09
  • @CetinBasoz can you elaborate a little more? I attempted to concatenate, but I think may have done it incorrectly. Commented Jun 10, 2020 at 14:42
  • @CetinBasoz could you start it off for me? I keep getting error messages. I must be missing something here. Commented Jun 11, 2020 at 10:48

1 Answer 1

2

This is how you would write a long string in VBA:

    StrQuery = "Select" & _
" case when srvprovid like '01%' then 'AL'" & _
"      WHEN srvprovid like '02%' then 'AK'" & _
"      WHEN srvprovid like '03%' then 'AR'" & _
" ..."

And this is what I suggest you to do instead (just a sample showing the idea, didn't write full code):

DECLARE @sample TABLE (srvProvId VARCHAR(10), id INT IDENTITY);
INSERT INTO @sample (srvProvId) VALUES 
('010'),
('01'),
('020'),
('030'),
('040');

DECLARE @states VARCHAR(1000) = 'AL,AK,AR,AZ,CA,CO,CT'; -- DE,DC,FL...
DECLARE @tally TABLE (id INT IDENTITY, abrv CHAR(2));

INSERT @tally (abrv)  
SELECT value FROM STRING_SPLIT(@states, ',') ;

SELECT * 
FROM @sample t1
LEFT JOIN @tally t2 ON t1.srvProvId LIKE RIGHT('0'+CAST(t2.id AS VARCHAR(2)),2)+'%';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.