text:
Tips for golfing in VBA
Similar to this, this, and this question...
What general tips do you have for golfing in VBA? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to VBA (e.g. "remove comments" is not an answer). Please post one tip per answer.
While I have worked with other languages, I'm strongest in VBA, and I don't see many golfers using VBA on this site.

Converted to Community Wiki as per policy.

Sorry that wasn't automatic on my part!

No trouble. Actually, they've taken the power to make questions CW away from users (you can still do answers, I think). You could flag for moderator attention, but as little activity as CodeGolf gets that is hardly necessary.

VBA is a relatively verbose language with few syntax shortcuts.  If you're going for best score, VBA may not be a good choice.  If you're looking to hone your skills, more power to ya.

@GigaWatt Honing my skills it is. Actually since playing around with different challenges, I've already picked up a few new tricks for working with VBA! I don't expect to win any real [tag:code-golf] challenges with VBA, but it's good practice. :-)

Variable Declaration
In most cases in VBA, you can leave out Option Explicit (often omitted by default, anyway) and skip Dim'ing many of your variables.
In doing so, this (96 Chars):
Option Explicit

Sub Test()
Dim S As String
Dim S2 As String
S = "Test"
S2 = S
MsgBox S2
End Sub

Becomes this (46 chars):
Sub Test()
S = "Test"
S2 = S
MsgBox S2
End Sub

If you need to use certain objects (for example, arrays), you may still need to Dim that variable.

Wait a second, you accepted your own answer to your question. Not cool, dude.

@TaylorScott It's a wiki post - no points, and in this case, there is not one single best answer. :) I accept the answer ~5 years ago to avoid having a flag in my questions list.

@TaylorScott also if you accept your own answer, you don't get +15 or +2 (for accepting)

Exploit the ByRef default when calling subs
It is sometimes possible to use a Sub call in place of a Function to save a few additional characters...
This (87 chars)
Sub a()
b = 0
Do Until b = 5
b = c(b)
Loop
End Sub
Function c(d)
c = d + 1
End Function

can be re-worked to (73 chars):
Sub a()
b = 0
Do Until b = 5
c b
Loop
End Sub
Sub c(d)
d = d + 1
End Sub

Notice this will NOT loop forever, though it appears you are never reassigning b's value.
The above doesn't use a Function call, but instead exploits the ByRef ("By Reference") functionality of the Sub call. What this means is the passed argument is the same variable as in the calling function (as opposed to a ByVal, "By Value" passing, which is a copy). Any modifications to the passed variable will translate back to the calling function.
By default, vba takes all arguments as ByRef, so there is no need to use up characters to define this.
The above example may not translate perfectly for you, depending on the return value of your function. (i.e. returning a different data type than what is passed), but this also allows for the possibility of getting a return value whilst still modifying your original variable.
For example:
Sub a()
b = 0
Debug.Print c(b) ' This will print 0, and b will equal 1.'
End Sub
Function c(d)
c = d
d = d + 1
End Function

Write and run the VBA code in the Immediate Window
The Immediate Window evaluates any valid VBA executable statement. Simply enter a statement in the Immediate Window as you would in the code editor. It quickly executes VBA code and it can save many additional characters because:

Putting the question mark (?) at the beginning of the statement tells the Immediate Window to display the result of your code.

You don't need to use a Sub and End Sub in your code.

Here is the example of VBA code in the Immediate Window to answer PPCG's post with tag code-golf : The Letter A without A
?Chr(88-23);

answered by Joffan.

Credit images: Excel Campus

That uses a REPL environment though? That means it is only a snippet, not a program or function

I think another example to add may be that you can also create variables inline; e.g a="value":?a first sets the value of a, then prints it.

Conditional Checks Before Looping
Some conditional checks are redundant when used in conjunction with loops. For example, a For loop will not process if the starting condition is outside the scope of the running condition.
In other words, this (49 chars):
If B > 0 Then
For C = A To A + B
'...
Next
End If

Can be turned into this (24 chars):
For C = A To A + B ' if B is 0 or less, then the code continues past Next, unabated.
'...
Next

The comment in the bottom is incorrect. If B =0 then the loop will be entered.  https://pastebin.com/97MBB7hq

Evaluate() And []
As has been pointed out previously, hard-coded range calls can be reduced using the square brackets [A1] notation. However it has many more uses than just that.
According to MSDN documentation, the Application.Evaluate() method takes a single argument, which is a Name, as defined by the naming convention of Microsoft Excel.
N.B. [string] is shorthand for Evaluate("string") (note the "" speech marks denoting string datatype), although there are a few important differences which are covered at the end.
So what does that all mean in terms of usage?
Essentially, [some cell formula here] represents a cell in an excel worksheet, and you can put pretty much anything into it and get anything out of it that you could with a normal cell
What goes in
In summary, with examples

A1-style references. All references are considered to be absolute references.

[B7] returns a reference to that cell
As references are absolute, ?[B7].Address returns "B$7$"

Ranges You can use the range, intersect, and union operators (colon,
space, and comma, respectively) with references.

[A1:B5] returns a range reference to A1:B5 (Range)
[A1:B5 A3:D7] returns a range reference to A3:B5 (Intersect)
[A1:B5,C1:D5] returns a range reference to A1:D5(technically A1:B5,C1:D5) (Union)

Defined names

User defined such as [myRange] referring to A1:G5
Automatic, like table names [Table1] (possibly less useful for codegolf)
Anything else you can find in the [Formulas]>[Name Manager] menu

Formulas

Very useful; any formula that can go in a cell can go in Evaluate() or []
[SUM(1,A1:B5,myRange)] returns arithmetic sum of values in the ranges myRange here refers to a workbook name not a VBA variable
[IF(A1=1,"true","false")] (1 byte shorter than vba equivalent Iif([A1]=1,"true","false"))
Array formulas[CONCAT(IF(LEN(A1:B7)>2,A1:B7&" ",""))] - joins all strings in range whose length is greater than 2 with a space

External references

You can use the ! operator to refer to a cell or
to a name defined in another workbook
[[BOOK1]Sheet1!A1] returns a range reference to A1 in BOOK1 or ['[MY WORKBOOK.XLSM]Sheet1!'A1] for the same in MY WORKBOOK
Note the ' for workbooks with spaces in their names, and the lack of extension for default named workbooks (BOOK+n)

Chart Objects (See the MSDN article)

NB I asked a question over on SO for this info, so take a look there for a better explanation
What comes out
Similar to what goes in, what comes out includes anything that a worksheet cell can return. These are the standard Excel data types (and their VBA equivalents):

Logical (Boolean)
Text (String)
Numerical (Double)
Error (Variant/Error) (these are non-breaking errors, ie. they do not halt code execution, ?[1/0] executes fine)

But there are a few things that can be returned which cells cannot:

Range reference (Range) (see above sections)
Arrays (Variant())

Arrays
As has been shown, [] can be used to evaluate array formulas which return one of the standard Excel data types; e.g. [CONCAT(IF(LEN(A1:B7)>2,A1:B7&" ",""))] which returns Text. However Evaluate can also return arrays of Variant type. These can be
Hardcoded:
[{1,2;3,4}] - outputs a 2D array: , is the column separator, ; separates rows. Can output a 1D array
Array Formulae:
[ROW(A1:A5)] - outputs a 2D array {1,2,3,4,5}, i.e (2,1) is the second item (yet some functions output 1D arrays)

For whatever reason, some functions do not return arrays by default

[LEN(A1:A5)] only outputs the Length of the text in the 1st cell of a range

However these can be coerced to give arrays

Split([CONCAT(" "&LEN(A1:A5))]) gives a 1D array 0 to 5, where the first item is empty
[INDEX(LEN(A1:A5),)] is another workaround, essentially you must employ an array handling function to get the desired array returning behaviour, similar to adding in a meaningless RAND() to make your worksheet formulae volatile.

I asked a question on SO to try to get some better info on this please edit/comment with better options if you find them

Evaluate() vs []
There are a few differences between Evaluate() and [] to be aware of

Strings vs hardcoded

Perhaps the most important difference, Evaluate takes a string input where [] required a hardcoded input
This means your code can build up the string with variables e.g. Evaluate("SUM(B1,1,"&v &",2)") would sum [B1],1,2 and variable v

Arrays
When returning an Array, only Evaluate can be used with an array index, so
v=Evaluate("ROW(A1:A5)")(1,1) ''#29 bytes

is equivalent to
i=[ROW(A1:A5)]:v=i(1,1) ''#23 bytes

Sorry for the mammoth post, if anyone feels they can make areas more concise/ if you have tips to add, then feel free. Also, although I researched some of this, a fair portion was found through experimenting in VBA, so if you spot mistakes of feel there's something missing, don't hesitate to comment/edit accordingly!

Actually the last section on arrays is a bit off - it can be used in the immediate window i=[ROW(A1:A5)]:v=i(2,1):?v

@TaylorScott So you can, I was totally unaware that you could set/ hold values in variables that weren't already defined, but I suppose that's because I'm still getting to grips with the Immediate window 1-liners. Have updated accordingly

Does this work with Match? I tried, but it always returns errors. I was passing an array instead of a range, though.

Combine Next Statements
Next:Next:Next

May be condensed down to
Next k,j,i

where the iterators for the For loops are i,j, and k - in that order.
For example the below (69 Bytes)
For i=0To[A1]
For j=0To[B1]
For k=0To[C1]
Debug.?i;j;k
Next
Next
Next

May be condensed down to 65 Bytes
For i=0To[A1]
For j=0To[B1]
For k=0To[C1]
Debug.?i;j;k
Next k,j,i

And as far as how this impacts formatting and indentation, I think the best approach to handling this is left aligning the next statement with the outer most for statement. Eg.
For i=0To[A1]
    For j=0To[B1]
        For k=0To[C1]
            Debug.?i;j;k
Next k,j,i

Reducing If Statements
When assigning a variable using a conditional If ... Then ... Else check, you can reduce the amount of code used by eliminating the End If by putting the entire check on one line.
For example, this (37 chars):
If a < b Then
c = b
Else
c = a
End If

Can be reduced to this (30 chars)
If a < b Then c = b Else c = a

If you have more than one nested conditional, you can minimize them this way as well:
If a Then If b Then If c Then Z:If d Then Y:If e Then X Else W Else V:If f Then U 'Look ma! No "End If"!

Note the : allows you to add more than one line/command within an If block.
In simple cases like this, you can usually also remove the Else by setting the variable in before the If check (25 chars):
c = a
If a < b Then c = b

Even better, the above can be further reduced to this using the IIf() function (20 chars):
c = IIf(a < b, b, a)

Prepare For Pixel Art
Pixel art is by far one of Excel's strongest areas, as there is no need to construct a canvas, as it is already there for you - all you need to do is make some small adjustments
1) Make the cells square
Cells.RowHeight=48

or, Alternatively, for 1 byte more, but far easier to work with
Cells.ColumnWidth=2

Depending on the context, you may be able to get away without having to resize your cells at all. With the default RowHeight of \$15\$ and ColumnWidth of \$8.09\$, the aspect ratio of a default cell is \$\approx415:124\$.
If you use this to calculate what range needs to be selected to draw a given shape you may be able to drastically reduce your bytecount.
Example:
Golfing the Ukrainian flag with the correct \$2:3\$ aspect ratio can golfed down from
Cells.RowHeight=48:[A1:BZ52].Interior.Color=55265:[A1:BZ26].Interior.Color=12015360

to
[A1:NH830].Interior.Color=55265:[A1:NH415].Interior.Color=12015360

2) Color the needed range
Any Range object may be colored by calling
`MyRangeObj`.Interior.Color=`ColorValue`

Note: this can and should be combined with other tricks noted on this wiki, such as referencing ranges by the use of the [] notation (eg [A1:R5,D6]) over the use of a Cells(r,c) or a Range(cellAddress) call. Further, as noted on this wiki, this may be combined with negative color value to golf down the size of color references

Quick References
Range Reference
Cell A1 may be referenced in any of the following ways
Range("A1")
Cells(1,1)
[A1]

and the Range A1:D4 may be referenced in any of the following ways
Range("A1:D4")
Range("A1").Resize(4,4)
Cells(1,1).Resize(4,4)
[A1].Resize(4,4)
[A1:D4]

Color Reference
Black  0
White  -1
Red    255
Aqua   -256

Simplify built-in functions
When using certain functions frequently, reassign them to a user-defined function.
The following code (127 chars) can be reduced from:
Sub q()
w = 0
x = 1
y = 2
z = 3
a = Format(w, "0.0%")
b = Format(x, "0.0%")
c = Format(y, "0.0%")
d = Format(z, "0.0%")
End Sub

to (124 chars):
Sub q()
w = 0
x = 1
y = 2
z = 3
a = f(w)
b = f(x)
c = f(y)
d = f(z)
End Sub
Function f(g)
f = Format(g, "0.0%")
End Function

Combining this with the ByRef trick and some autoformatting tricks, you can save even more characters (down to 81):
Sub q
w=0
x=1
y=2
z=3
f w
f x
f y
f z
End Sub
Sub f(g)
g=Format(g,"0.0%")
End Sub

Do this judiciously, as VBA takes up a lot of characters to define a Function. The second code block would actually be larger than the first with any number fewer Format() calls.

in the last one, you do not need the assignment call, meaning that a = f(w) can be reduced to f w

Reduce Range("A1") and Like Calls
Range("A1").Value(17 Bytes) and the simpler Range("A1")(11 Bytes) may be reduced down to [A1] (4 Bytes)

Or in general, the use of [] to replace Evaluate() in VBA is a lot more versatile than just range calls. E.g you can use it to replace WorksheetFunction.FuncName(args) with just [FuncName(args)], such as ?[SUMPRODUCT({1,3,5},{2,7,-1})] or the very useful [MIN(1,2,3)]/[MAX(1,2,3)]

Greedo, that is an incredibly important functionality that I was not aware of you should add this as its own answer.

Sure thing, I'll write something up shortly. Yes Evaluate("str") or shorthand [str] is very powerful in VBA, I've only recently found out, and I'm guessing it will be useful for golfing too!

Very useful, enoughso that I am going back through my answers to see if I can drop my bytecount on any because of it

STDIN and STDOUT

Inputting to Subroutines and Functions via input variables
Public Sub A(ByRef B as String)

May be reduced down to
Sub a(b$)

The Public and ByRef calls are the default for VBA and thus implicit, and may (almost) always be dropped.
The type literal $ forces b to be of the type String.
Other type literals

! Single
@ Currency
# Double
% Integer
$ String
& Long
^ LongLong (64 Bit Only)

Furthermore, it is generally accepted that you may leave the input variable as the default type, Variant and leave any type-based errors unhandled. Eg. Sub E(F) in which F is expected to be of type Boolean[] (which would be passed to the routine like E Array(True, False, False))
Inputting to Subroutines and Immediate Window Functions via Cells
VBA does not have a fully functional console and thus does not have any official STDIN, and thus allows for some play with passing input.
In excel, it is generally accepted to take input from a cell or range of cells, which may be done like
s=[A1]

which implicitly puts the .value from the cell [A1] (which may also be referenced as cells(1,1) or range("A1")
Example Problem: Display the input in a messagebox
Via Subroutine Sub A:msgbox[A1]:End Sub
Via Immediates Window Function msgbox[A1]
Inputting Via Conditional Compilation Arguments
VBA Projects support taking arguments from the command line or via the VBAProject Properties (view via the project explorer -> [Your VBA Project] -(Right Click)-> VBAProject Properties -> Conditional Compilation Arguments)
This is largely useful for Error Code Challenges
Given the Conditional Compilation Argument n=[some_value] this allows for executing code that will produce an error code, based off of the value of n.
note, this calls for an addition of 2 bytes to your code for the n= in the conditional compilation arguments section of the VBAProject Properties Pane.
Example Code
...
#If n=3 then
return ''  Produces error code '3', Return without GoSub
#ElseIf n=20 then
resume ''  Produces error code '20', Resume without Error
#EndIf
...

Outputting Via Function Value
Not Much to say here, the general form of quoted below is about as compact as it can be made.
Public Function A(b)
    ...
    A=C
End Function

NOTE: in the vast majority of cases it is more byte convert the method to a subroutine and output to the VBE immediates window (see Below)
Outputting From Subroutines and Functions via the VBE Immediates Window
Outputting to the VBE immediates window (AKA the VBE Debug Window) is a common output method for VBA for text based challenges, however, it is important to remember that the Debug.Print "Text" call may be substantially golfed.
Debug.Print "Text"

is functionally identical to
Debug.?"Text"

as ? autoformats to Print.
Outputting from Subroutines and VBE Immediates Window functions via Other Methods
On rare occasion, when the situation is just right, you may take input from some of the more trivial inputs available to VBA such as the font size adjuster, font selector, and zoom. (Eg. Emulating the Word Font Size Selector)

Remove Spaces
VBA will auto-format to add a lot of spacing that it doesn't actually need. There' an answer on meta that makes a lot of sense to me why we can discount bytes added by auto-formatting. It's important to always verify you haven't removed too much, though. For an example, here's an answer of mine that was reduced almost 22% just by removing spaces:
Original version: (188 bytes)
Sub g(n)
For i = 0 To 1
For x = -3 To 3 Step 0.05
y = n ^ x * Cos(Atn(1) * 4 * x)
If y < m Then m = y
If i = 1 Then Cells(500 * (1 - y / m) + 1, (x + 3) * 100 + 1) = "#"
Next
Next
End Sub

Reduced version: (146 bytes)
Sub g(n)
For i=0To 1
For x=-3To 3Step 0.05
y=n^x*Cos(Atn(1)*4*x)
If y<m Then m=y
If i=1Then Cells(500*(1-y/m)+1,(x+3)*100+1)="#"
Next
Next
End Sub

If you copy / paste the reduced version into VBA, it will automatically expand into the original. You can play around with where it is valid to remove spaces. The ones I've found so far all seem to follow the pattern where VBA is expected a certain command to appear because, without it, it's not valid code. Here are some that I've found so far:

Before and after any mathematical operation: +-=/*^ etc.
Before To and Step in a For statement: For x=-3To 3Step 0.05
Actually, before any reserved word (To, &, Then, etc.) if it's preceded by a literal such as a number, ), ?, %, etc.
After the & when combining strings: Cells(1,1)=Int(t)&Format(t,":hh:mm:ss")
After function calls: If s=StrReverse(s)Then
Within function calls: Replace(Space(28)," ",0)

What's the rule on added non-space characters through auto-formatting. Something like ? vs Print I see is acceptable, but putting at type declaration like & immediately after a variable eg Debug.?a&"z" gives Debug.Print a&; "z". The ; character added is essential for the code to run - is this still allowed?

@Greedo I see it the way the meta answer described it: If you can copy / paste it into the editor and the code will run, it's OK. I.E., if VBA automatically adds the character back when you paste the code, then it's OK.

@EngineerToast you can actually drop one more byte off of your example: If i=1 Then  may become If i=1Then  because, as a general rule a reserved word that follows a literal, be that a number, ), ?, %,.. etc, does not need to be separated by a space

@EngineerToast, you can also drop a byte from your third bullet point as you can drop the spaces between a ) (or any other non-number literal) and &

Is Step.05 fine or only Step .05?

Ending For Loops
When using For loops, a Next line does not need a variable name (though it is probably better to use in normal coding).
Therefore,
For Variable = 1 to 100
    'Do stuff
Next Variable

can be shortened to:
For Variable = 1 to 100
    'Do stuff
Next

(The savings depends on your variable name, though if you're golfing, that's probably just 1 character + 1 space.)

2 characters, don't forget to count the space!

I happen to almost never identify the variable, even in normal code!

Multiple If .. Then checks
As in other languages, multiple If checks can usually be combined into a single line, allowing for the use of And/Or (i.e. &&/|| in C and others), which in VBA replaces both a Then and an End If.
For example, with a nested conditional (93 chars):
'There are MUCH easier ways to do this check (i.e. a = d).
'This is just for the sake of example.
If a = b Then
    If b = c Then
        If c = d Then
            MsgBox "a is equal to d"
        End If
    End If
End If

can become (69 chars):
If a = b And b = c And c = d Then
    MsgBox "a is equal to d"
End If

This also works with non-nested conditionals.
Consider (84 chars):
If a = b Then
    d = 0
End If

If c = b Then
    d = 0
End If

This can become (51 chars):
If a = b Or c = b Then
    d = 0
End If

in If - then statements the "End - if" part is optional provide you write the code in the single line.

@newguy Correct. See also this other answer: https://codegolf.stackexchange.com/a/5788/3862

The statement above can be condensed further to d=iif(a=b or c=b,0,d)

Using With (Sometimes! See footnote)
Using the With statement can reduce your code size significantly if you use some objects repeatedly.
i.e. this (80 chars):
x = foo.bar.object.a.value
y = foo.bar.object.b.value
z = foo.bar.object.c.value

can be coded as (79 chars):
With foo.bar.object
    x = .a.value
    y = .b.value
    z = .c.value
End With

The above isn't even the best-case scenario. If using anything with Application, such as Excel.Application from within Access, the improvement will be much more significant.

*Depending on the situation, With may or may not be more efficient than this (64 chars):
Set i = foo.bar.object
x = i.a.value
y = i.b.value
z = i.c.value

Converting a string to a number
If you have a string value such as "1" (note a string, not 1), you can use a number of different conversions to get this as a manipulable number.
y=Val(x)
y=Int(x)
y=CLng(x)
y=CDbl(x)
\$\cdots\$
You can convert it using a math operation, like so:
y=x+0
y=x*1
These usually work in most cases, and only costs 5 characters, as opposed to 8 from the smallest example above.
However, the smallest way to do this conversion only is to do the following:
Dim y As Integer
x="123"
y=x

where y=x is a 3 char conversion, but this requires the explicit Dimming of y, which is often generally unnecessary when golfing in the first place.

As noted in the comments, the above can be further reduced as:
Dim y%
x="123"
y=x

You can use identifier type character %, i.e. Dim y%, to save 10 bytes.

Actually, you don't need Dim, just x="123":y%=x will work

Split a string into a character array
Sometimes it can be useful to break apart a string into individual characters, but it can take a bit of code to do this manually in VBA.
ReDim a(1 To Len(s))
' ReDim because Dim can't accept non-Const values (Len(s))
For i = 1 To Len(s)
    a(i) = Mid(s, i, 1)
Next

Instead, you can use a single line, relatively minimal chain of functions to get the job done:
a = Split(StrConv(s, 64), Chr(0))

This will assign your string s to Variant array a. Be careful, though, as the last item in the array will be an empty string (""), which will need to be handled appropriately.
Here's how it works: The StrConv function converts a String to another format you specify. In this case, 64 = vbUnicode, so it converts to a unicode format. When dealing with simple ASCII strings, the result is a null character (not an empty string, "") inserted after each character.
The following Split will then convert the resulting String into an array, using the null character Chr(0) as a delimiter.
It is important to note that Chr(0) is not the same as the empty string "", and using Split on "" will not return the array you might expect. The same is also true for vbNullString (but if you're golfing, then why would you use such a verbose constant in the first place?).

You should mention that the resulting array has an additional empty string at the end.

@Howard Yes, I should. It was in my head while I was typing this up, must have slipped my mind.

Reduce Debug.Print and Print calls
Debug.Print [some value]

(12 Bytes; note the trailing space) may be reduced to
Debug.?[some value]

(7 Bytes; note the lack of trailing space).
Similarly,
Print

(6 Bytes) may be reduced to
?

(1 Byte).
Furthermore, when operating in the context of an anonymous VBE immediate window function the Debug statement may be dropped entirely, and instead printing to the VBE immediate window via ? may be assumed to be STDIN/STDOUT
Special characters
When printing strings you can also use special characters in place of &. These allow for alternate formats in what's printed or whitespace removal
To join variable strings, instead of
Debug.Print s1 &s2

You can use a semicolon ;
Debug.?s1;s2

This semicolon is the default behaviour for consecutive strings, as long as there is no ambiguity
So these are valid:
Debug.?s1"a"
Debug.?"a"s1

But not
Debug.?s1s2 'as this could be interpreted as a variable named "s1s2", not 2 variables
            'use Debug.?s1 s2 instead (or s1;s2)
Debug.?"a""b" 'this prints a"b, so insert a space or ; for ab

Note that a ; at the end of a line suppresses a newline, as newlines are by default added after every print. Counting bytes returned by VBA code is under debate
To join with a tab use a comma , (actually 14 spaces, but according to )
Debug.?s1,s2 'returns "s1              s2"

Finally, you can use type declarations to join strings instead of ;, each having its own slight effect on formatting. For all of the below a = 3.14159 is the first line
Debug.?a&"is pi" -> " 3 is pi" 'dims a as long, adds leading and trailing space to a
Debug.?a!"is pi" -> " 3.14159 is pi" 'dims a as single, adds leading and trailing space
Debug.?a$"is pi" -> "3.14159is pi" 'dims a as string, no spaces added

Quick Note on Formatting
Because StackExchange uses Markdown and Prettify.js it is possible to add a language flag to your coding answers, which generally makes them look more professional. While I cannot guarantee that this will make you any better at golfing in VBA, I can guarantee that it will make you look like you are.
Adding either of the flags below will transform
Public Sub a(ByRef b As Integer) ' this is a comment

to
Public Sub a(ByRef b As Integer) ' this is a comment

VBA Language Tags
<!-- language: lang-vb -->
<!-- language-all: lang-vb -->
Note: the latter transforms all code segments in your answer, while the prior transforms only the immediately following code segments

lang-vb eh? - Strange that that formats better than lang-vba for vba answers.

@Greedo, that is because while lang-vba will provide highlighting, its actually just the default highlighting. Apparently VBA has not actually been implemented in Prettify.js, so we'll have to stick with the VB highlighting

Infinite Loops
Consider replacing
Do While a<b
'...
Loop

or
Do Until a=b
'...
Loop

with the antiquated but lower byte count
While a<b
'...
Wend

If you need to exit a Sub or Function prematurely, then instead of Exit ...
For i=1To 1000
    If i=50 Then Exit Sub
Next

consider End
For i=1To 1E3
    If i=50 Then End
Next

Note that End halts all code execution and clears out any global variables, so use wisely

You should consider rewriting the last section (For and End) to reflect that the case 100 will never be met and adds an unecessary byte

Also, while this is very legible, you may consider removing the whitespace to show the possible benefits of these methods better (it is always good to abuse the autoformatting in VBA for codegolfing)

Address Sheets By Name
Instead of Addressing a WorkSheet object by calling
Application.ActiveSheet
''  Or
ActiveSheet

One may use
Sheets(n)  ''  Where `n` is an integer
''  Or
[Sheet1]

Or More preferably one may access the object directly and use
Sheet1

Use Spc(n) over Space(n), [Rept(" ",n)] or String(n," ")
When trying to insert several spaces of length n, use
Spc(n)              ''  6  bytes

over
B1=n:[Rept(" ",B1)] ''  19 bytes
String(n," ")       ''  13 bytes
Space(n)            ''  8  bytes
Note: I am not sure why, but it seems that you cannot assign the output of Spc(n) to a variable, and that it must rather be printed directly - so in certain cases Space(n) is still the best way to go.

Use a helper Sub to Print
If the code requires using more than six Debug.? statements you can reduce bytes by replacing all Debug.? lines with a call to a Sub like the one below.  To print a blank line you need to call p "" since a parameter is required.
Sub p(m)
Debug.?m
End Sub

To print a new line with that you would only need p"" or if it can be unterminated, p". However, in the vast majority of cases where this may apply, it makes more sense to use a string variable and only print the string variable at the end.

In Excel, Create Numeric Arrays by Coercing Ranges
When a constant single dimensional set of numerics of mixed length, \$S\$ is needed, it shall be more efficient to use [{...}] notation to declare a range and then coerce that into a numeric array rather than to use the  Split(String) notation or similar.
Using this method, a change of \$\Delta_\text{byte count} =-5~\text{bytes}\$ shall be accrued for all \$S\$.
Example
For instance,
x=Split("1 2 34 567 8910")

may be written as
x=[{1,2,34,567,8910}]

It is further worth noting that while this method does not allow for direct indexing, it does allow for iteration over the for loop directly, ie
For Each s In[{1,3,5,7,9,2,4,6,8}]

Implicit type convertion - Double to Integer
This trick can spare you the rounding step if you have a floating point number and you need an integer index.
Consider you have an array m:
Dim m(10)

You can use Double for array indices and they will be coerced to Integer:
For j=1.1 To 10.1 Step 1.1
m(j)=j
Debug.?m(j)
Next

For instance, this trick could be used to randomly generate indices:
Debug.?m(Rnd*9+1)

The same applies also to the cell indices:
For j = 1.1 To 10.1 Step 1.1
Cells(j, 1) = j
Cells(Round(j), 2) = Round(j)
Next

Here is the output (note that the value is rounded to the nearest integer, therefore the 5th row is empty):

-----
*in R too, one can use doubles for the indexing without explicit conversion.

Use Array() Choose() instead of Select or If...Then
When assigning a variable based on a the value of another variable, it makes sense to write out the steps with If...Then checks, like so:
If a = 1 Then
b = "a"
ElseIf a = 2 Then
b = "c"
'...
End If

However, this can take up a lot of code space if there are more than one or two variables to check (there are still generally better ways to do even that anyway).
Instead, the Select Case statement helps reduce the size of the checks by encasing everything in one block, like so:
Select Case a
Case 1:
b = "a"
Case 2:
b = "c"
'...
End Select

This can lead to much smaller code, but for very simple cases such as this, there is an even more efficient method: Choose() This function will pick a value from a list, based on the value passed to it.
b = Choose(a,"a","c",...)

The option to select (a in this case) is an integer value passed as the first argument. All subsequent arguments are the values to choose from (1-indexed, like most VBA). The values can be any data type so long as it matches the variable being set (i.e. objects don't work without the Set keyword) and can even be expressions or functions.
b = Choose(a, 5 + 4, String(7,"?"))

An additional option is to use the Array function to get the same effect while saving another character:
b = Array(5 + 4, String(7,"?"))(a)

An interesting and possibly very beneficial use for golfing is to use this in conjunction with an IIf() or another Choose(): A1=IIf(a=Choose(b,c,d,e),Choose(Choose(f,g,h,i),j,k,l),Choose(IIf(m=n,Choose(p,q,r,s),IIf(t=u,v,w)),x,y,z))

Use Truthy and Falsey Variables in conditionals
Sometimes called implicit type conversion - directly using a number type in a If,[IF(...)] or IIf(...) statement, by using the truthy and falsey nature of that number can absolutely save you some bytes.
In VBA, any number type variable that is non-zero is considered to be truthy ( and thus zero, 0, is the only value falsey) and thus
If B <> 0 Then
    Let C = B
Else
    Let C = D
End If

may be condensed to
If B Then C=B Else C=D

and further to
C=IIf(B,B,D)

Bit-Shifted RGB Values
Because of the way that Excel handles colors, (unsigned, 6-character hexadecimal integer) you can make use of negatively signed integers, of which excel will only use the right 6 bytes to assign a color value
This is a bit confusing so some examples are provided below
Lets say you want to use the color white, which is stored as
rgbWhite

and is equivalent to
&HFFFFFF ''#value: 16777215

to golf this down all we need to do is find a negative hexadecimal value which terminates in FFFFFF and since negative Hex values in must be in the format of FFFFXXXXXX (such that X is a valid hexadecimal) counting down from FFFFFFFFFF (-1) to FFFF000001 (-16777215)
Knowing this we can generalize that the formula
Let Negative_Color_Value = -rgbWhite + Positive_Color_Value - 1
                         = -16777215 + Positive_Color_Value - 1
                         = -16777216 + Positive_Color_Value

Using this, some useful conversions are
rgbWhite = &HFFFFFF = -1
rgbAqua  = &HFFFF00 = -256
16747627 = &HFF8C6B = -29589

Good to know what was going on there, I just discovered it by accident in that question - but this clear explanation shows exactly how it works. Another thing to bear in mind is that certain key colours can be reduced with mathematical operators; rgbWhite=2^24-1 although could  possibly be reduced further if you miss off the -1 to get roughly there

In fact, here is a list of colours with their mathematical representations, which are shorter than either the positive or negative decimal versions: &000080: 2^7, &000100: 2^8, &000200: 2^9, &000400: 2^10, &000800: 2^11, &001000: 2^12, &002000: 2^13, &004000: 2^14, &008000: 2^15, &010000: 2^16, &01FFFF: 2^17-1, &020000: 2^17, &03FFFF: 2^18-1, &040000: 2^18, &07FFFF: 2^19-1, &080000: 2^19, &0FFFFF: 2^20-1, &100000: 2^20, &1FFFFF: 2^21-1, &3FFFFF: 2^22-1, &400000: 2^22, &7FFFFF: 2^23-1 n.b. not necessarily complete, but I think I did a fairly thorough job

Exponentiation and LongLongs in 64-Bit VBA
The general form of exponentiation,
A to the power of B

Can be represented as in VBA as
A^B

But Only in 32-Bit Installs of Office, in 64-Bits installs of Office, the shortest way that you may represent without error this is
A ^B

This is because in 64-Bit versions of VBA ^ serves as both the exponentiation literal and the LongLong type declaration character. This means that some rather odd-looking but valid syntax can arise such as
a^=2^^63^-1^

which assigns variable a to hold the max value of a Longlong

Omit terminal " when printing to Immediate Window
Given the function below, which is to be used in the debug window
h="Hello":?h", World!"

The Terminal " may be dropped for -1 Byte, leaving the string unclosed and the program shall execute the same, without error
h="Hello":?h", World!

Even more surprising than this is that this may be done within fully defined subroutines.
Sub a
h="Hello":Debug.?h", World!
End Sub

The subroutine above runs as expected and autoformats to
Sub a()
h = "Hello": Debug.Print h; ", World!"
End Sub

Compress Byte Arrays as String

For challanges that require the solution to hold constant data, it shall may be useful to compress that data as a single string and to then iterate across the string to fetch the data.
In VBA, any byte value may be directly converted to a character with
Chr(byteVal)

And a long or integer value may be converted to two characters with
Chr(longVal / 256) & Chr(longVal Mod 256)

So for a byte array a compression algorithm would look something like
For Each Var In bytes
    Select Case Var
        Case Is = Asc(vbNullChar)
            outstr$ = outstr$ & """+chr(0)+"""
        Case Is = Asc(vbTab)
            outstr$ = outstr$ & """+vbTab+"""
        Case Is = Asc("""")
            outstr$ = outstr$ & """"""
        Case Is = Asc(vbLf)
            outstr$ = outstr$ & """+vbLf+"""
        Case Is = Asc(vbCr)
            outstr$ = outstr$ & """+vbCr+"""
        Case Else
            outstr$ = outstr$ & Chr$(Var)
    End Select
Next
Debug.Print "t="""; outstr$

Noting that the Select Case section is implemented due to the characters which may not be stored as literals in the string.
From the resulting string, which will look something like
t="5¼-™):ó™ˆ"+vbTab+"»‘v¶<®Xn³"+Chr(0)+"~Î¯šÐ‘š;$ÔÝ•óŽ¡¡EˆõW'«¡*{ú{Óx.OÒ/R)°@¯ˆ”'®ïQ*<¹çu¶àªp~ÅP>‹:<«a°;!¾y›/,”Ì#¥œ5*B)·7

The data may then be extracted using the Asc and Mid functions, eg
i=Asc(Mid(t,n+1))

Use Improper Constants

VBA allows, in some cases, for the use of unlisted or improper constants in expressions which require constant values. These are often legacy values, and shorter in length than the proper values.
For example the values below may be used when letting a value be held by the  rng.HorizantalAlignment property.
\$
\small
\begin{align}
\textbf{Improper}   &&\textbf{Proper} && \textbf{General Constant}\hspace{1.3cm}&&& \texttt{xlHAlign}~~\textbf{Constant}   \\\hline
1\hspace{1.25cm}    && 1\hspace{.7cm} && \texttt{xlGeneral}\hspace{2.95cm}      &&& \texttt{xlHAlignGeneral}               \\
2\hspace{1.25cm}    && -4131          && \texttt{xlLeft}\hspace{3.6cm}         &&& \texttt{xlHAlignLeft}                  \\
3\hspace{1.25cm}    && -4108          && \texttt{xlCenter}\hspace{3.18cm}       &&& \texttt{xlHAlignCenter}                \\
4\hspace{1.25cm}    && -4152          && \texttt{xlRight}\hspace{3.39cm}           &&& \texttt{xlHAlignRight}                 \\
5\hspace{1.25cm}    && 5\hspace{.7cm} && \texttt{xlFill}\hspace{3.61cm}         &&& \texttt{xlHAlignFill}                  \\
6\hspace{1.25cm}    && -4130          && \texttt{xlJustify}\hspace{2.97cm}       &&& \texttt{xlHAlignJustify}               \\
7\hspace{1.25cm}    && 7\hspace{.7cm} && \texttt{xlCenterAcrossSelection}       &&& \texttt{xlHAlignCenterAcrossSelection} \\
8\hspace{1.25cm}    && -4117          && \texttt{xlDistributed}\hspace{2.15cm}   &&& \texttt{xlHAlignDistributed}
\end{align}
\$
This means, for example that setting a cell to having its text centered with
rng.HorizantalAlignment=-4108

may be shortened down to
rng.HorizantalAlignment=3

by replacing the improper constant value 3 for the proper value -4108. Note that if you fetch the rng.HorizantalAlignment property value, it will return the proper value. In this case, that would be -4108.

Automate Testing for Immediate Window Functions
This response seeks to make the testing of Anonymous VBE Immediate Window Functions that take input from the range [A1] and output to the immediate window.
Testing immediate window functions can take hours if done by hand, so rather than doing that, take advantage of the Microsoft Visual Basic for Applications Extensibility 5.3 reference and and helper function to automate testing these functions. (you will need to give Excel access to the VBE project model - remember to revoke this access when you are done!)
Example
As sample of code that can do this is shown below - must be pasted into the top of Module1 to function.
Private Sub helper()
    ''  At runtime, the program will be pasted below, with `?` replaced as `Debug.Print`

    ''  At runtime, the program will be pasted above
End Sub

Sub cgTester(ByVal program As String, ParamArray testCases())

    ''  Using `MicroSoft Visual Basic for Applications Extensibility 5.3` and
    ''  having access to the VBA Project Model

    Dim testCase    As Variant, _
        vbProj      As VBIDE.VBProject, _
        vbComp      As VBIDE.VBComponent

    Debug.Print vbCrLf; vbCrLf; program; vbCrLf; vbCrLf

    Set vbProj = Application.ThisWorkbook.VBProject
    Set vbComp = vbProj.VBComponents.Item("Module1")
    Debug.Assert (vbComp.CodeModule.Lines(2, 1) = _
        "    ''  At runtime, the program will be pasted below, with `?` replaced as `Debug.Print`")
    Debug.Assert (vbComp.CodeModule.Lines(4, 1) = _
        "    ''  At runtime, the program will be pasted above")

    ''  "paste" in the program above, where indicated
    Call vbComp.CodeModule.InsertLines(3, Replace(program, "?", "Debug.?"))
    Call vbComp.CodeModule.DeleteLines(4, 1)

    For Each testCase In testCases
        Let [A1].Value = testCase
        Debug.Print "<- `"; testCase; "`"; vbCrLf; "->";
        Call helper                                         '' Call the program
        Debug.Print                                         '' Print for spacing
    Next testCase

    Call vbComp.CodeModule.InsertLines(3, "")   ''  Clear out the program to be ready for next use
    Call vbComp.CodeModule.DeleteLines(4, 1)
End Sub

Usage
Shown as used on my solution to the Facey McFaceface question.
program = "b=[Left(Upper(A1))]+Mid([Lower(A1)],2):l=len(b):y=[Right(A1)=""y""]:?b;IIf(y,"""",""y"")"" Mc""IIf(y,Left(b,l-1+(InStrRev(b,""e"")=l-1)),b)""face"

cgTester program, "boat", "Face", "Dog", "Family", "Lady", "Donkey", "Player", "yyy", "DJ Grand Master Flash"

b=[Left(Upper(A1))]+Mid([Lower(A1)],2):l=len(b):y=[Right(A1)="y"]:?b;IIf(y,"","y")" Mc"IIf(y,Left(b,l-1+(InStrRev(b,"e")=l-1)),b)"face

<- `boat`
->Boaty McBoatface

<- `Face`
->Facey McFaceface

<- `Dog`
->Dogy McDogface

<- `Family`
->Family McFamilface

<- `Lady`
->Lady McLadface

<- `Donkey`
->Donkey McDonkface

<- `Player`
->Playery McPlayerface

<- `yyy`
->Yyy McYyface

<- `DJ Grand Master Flash`
->Dj grand master flashy McDj grand master flashface

Use base64 Compression
With the Microsoft XML, v3.0 Reference, MSXML2.DOMDocument objects may be used decode a base64 string into a byte array, which may be used as necessary for the question.
The most basic code needed to perform this is
Set d=New MSXML2.DOMDocument
Set d=d.createElement("b64")
d.DataType="bin.base64
d.Text="[Your base64 String]
b=d.nodeTypedValue

where b is the resulting byte array (0-indexed). More information about the basis for this method and about encoding/decoding in base64 in VBA may be found here
I've written up a short segment of code to generate the above snippet of code from a supplied byte array
Public Function GolfBase64Code(ByRef bytes() As Byte, _
                   Optional ByVal DOMname As String = "d", _
                   Optional ByVal bytesName As String = "b")

    Debug.Assert DOMname <> "" And bytesName <> ""

    Dim DOM             As New MSXML2.DOMDocument, _
        node            As MSXML2.IXMLDOMElement, _
        lines(0 To 4)   As String, _
        base64String    As String

    Set node = DOM.createElement("b64")
    Let node.DataType = "bin.base64"
    Let node.nodeTypedValue = bytes
    Let base64String = Replace(node.Text, vbLf, "")

    Set node = Nothing
    Set DOM = Nothing

    Let lines(0) = "Set " & DOMname & "=New MSXML2.DOMDocument"
    Let lines(1) = "Set " & DOMname & "=" & DOMname & ".createElement(""b64"")"
    Let lines(2) = DOMname & ".DataType=""bin.base64"
    Let lines(3) = DOMname & ".Text=""" & base64String
    Let lines(4) = bytesName & "=" & DOMname & ".nodeTypedValue"

    Let GolfBase64Code = VBA.Join(lines, vbLf)
End Function

And an example to show the usage of the function
Private Sub GolfBase64CodeExample()

    Const hexString As String = _
        "030A37BE2F9B072B0E3CF59B8A911B0B0EBD9378B83EB05A70B50280D0B19CD2" & _
        "2093209C3D1126D6DF1997F590A3A3478AF7085929ADA32C7DFC0D7DD57A3051" & _
        "D431542BB242B1148A962914B0F1532C04130A093EBBE9161877B8E2AC7280C7" & _
        "52408D3C3EAFAD631E14B23D238FC07BAF9D312E96CE25A79E372C442BB92139"

    Dim bytes(0 To 127) As Byte, _
        i               As Integer

    For i = 0 To 127 Step 1
        bytes(i) = Application.WorksheetFunction.Hex2Dec(Mid(hexString, 2 * i + 1, 2))
    Next i

    cat "''''''''''''''''''''''''''''''''''''''''"
    cat "''"
    cat "'' Previous Code"
    cat "''"
    cat "''''''''''''''''''''''''''''''''''''''''"
    cat
    cat "w=Evaluate(""=Hex2Dec(""""""&Mid(""" & hexString & """,4*p+1,4)&"""""")"")"
    cat
    cat "'  From https://codegolf.stackexchange.com/revisions/127105/39"
    cat
    cat "''''''''''''''''''''''''''''''''''''''''"
    cat "''"
    cat "'' Golfed Code (-1 byte)"
    cat "''"
    cat "''''''''''''''''''''''''''''''''''''''''"
    cat
    cat GolfBase64Code(bytes, "a", "b")
    cat "w=b(2*p)*256+b(2*p+1)"
    cat
    cat "'  From https://codegolf.stackexchange.com/revisions/127105/40"

End Sub

Private Sub cat(Optional ByRef value As Variant = "")
    Debug.Print value
End Sub

Output from the above tester subroutine above
''''''''''''''''''''''''''''''''''''''''
''
'' Previous Code
''
''''''''''''''''''''''''''''''''''''''''

w=Evaluate("=Hex2Dec("""&Mid("030A37BE2F9B072B0E3CF59B8A911B0B0EBD9378B83EB05A70B50280D0B19CD22093209C3D1126D6DF1997F590A3A3478AF7085929ADA32C7DFC0D7DD57A3051D431542BB242B1148A962914B0F1532C04130A093EBBE9161877B8E2AC7280C752408D3C3EAFAD631E14B23D238FC07BAF9D312E96CE25A79E372C442BB92139",4*p+1,4)&""")")

'  From https://codegolf.stackexchange.com/revisions/127105/39

''''''''''''''''''''''''''''''''''''''''
''
'' Golfed Code (-1 byte)
''
''''''''''''''''''''''''''''''''''''''''

Set a=New MSXML2.DOMDocument
Set a=a.createElement("b64")
a.DataType="bin.base64
a.Text="Awo3vi+bBysOPPWbipEbCw69k3i4PrBacLUCgNCxnNIgkyCcPREm1t8Zl/WQo6NHivcIWSmtoyx9/A191XowUdQxVCuyQrEUipYpFLDxUywEEwoJPrvpFhh3uOKscoDHUkCNPD6vrWMeFLI9I4/Ae6+dMS6WziWnnjcsRCu5ITk=
b=a.nodeTypedValue
w=b(2*p)*256+b(2*p+1)

'  From https://codegolf.stackexchange.com/revisions/127105/40


text:
Implement a One-Time Pad
Background
A one-time pad is a form of encryption that has been proven impossible to crack if used properly.
Encryption is performed by taking a plaintext (comprised of only letters A-Z) and generating a random string on the same length (also only letters). This string acts as the key. Each character in the plaintext is then paired up with the corresponding character in the key. The ciphertext is computed as follows: For each pair, both characters are converted to numbers (A=0, B=1, ... Z=25). The two numbers are added modulo 26. This number is the converted back into a character.
Decryption is exactly the opposite. The characters in the ciphertext and key are paired up and converted to numbers. The key is then subtracted from the ciphertext modulo 26, and the result is converted back into a character A-Z.
The Challenge
Your challenge is to write the shortest program possible that can both encrypt and decrypt a one-time pad.
On the first line of input (to STDIN), there will be either the word "ENCRYPT" or the word "DECRYPT".
If the word is encrypt, then the next line will be the plaintext. Your program should output two lines (to STDOUT), the first being the key, and the second being the ciphertext.
If the word is decrypt, your program will get two more line of input. The first line will be the key, and the second line will be the ciphertext. You program should output one line, which will be the plaintext that has been decrypted.
The plaintext, ciphertext, and key should always consist of uppercase letters A-Z. They will always be a single line and contain no whitespace.
The key should always be random. No large parts of it should repeat between runs, and there should be no patterns that can be found in the text.
Two simple examples:
ENCRYPT
HAPPYBIRTHDAY
>ABKJAQLRJESMG
>HBZYYRTICLVME

DECRYPT
ABKJAQLRJESMG
HBZYYRTICLVME
>HAPPYBIRTHDAY

The > represents which lines are output, so you don't have to print that symbol as output.

Not to criticize the challenge on it's own merits (which are fine), but I am going to criticize the cryptography here. What you are describing is a "stream cipher" as it depends on a PRNG (unless your computer has access to a source or real randomness (and if the linux implementation of /dev/urandom counts is a matter of some debate)), and having the key developed at enciphering time defeats the only really good use for a OTP which is time shifting of secure communications.

Also, all challenges are language agnostic by default, so I've removed that tag.

@dmckee Regarding your first comment, I agree, which is why I do not intend to use these answers to secure my communications.

this would have been more fun IMO to leave randomness out of the problem; given a source of randomness (/dev/random, haveged), encrypt by xoring the ords with the bytes and decrypt by xoring them with the key. https://gist.github.com/5078264 the key or the randomness can be read from stdin, the message or cyphertext can be a filename argument.

@PhiNotPi I have a suggestion. Why not give a bonus if they use a truly random source (like /dev/hwrng, instead of using pseudo random (which technically makes it broken.)

GolfScript, 53 chars
n%(0=2%{~.,[{26rand 65+}*]:K]}*zip{{-}*~)26%65+}%K]n*

This is a task for which GolfScript seems just about perfectly suited.
To keep the code short, I'm using the same code for both encryption and decryption: to decrypt, I subtract the key from the ciphertext, while for encryption, I first generate a random ciphertext and then subtract the plaintext from it.  Even so, the extra code for implementing encryption mode takes just a little over half the length of the program.
De-golfed version with comments:
n %             # split input into an array of lines

# KEY GENERATION FOR ENCRYPTION MODE:
(               # extract the first line from the array
0 = 2 %         # check if the first char of that line is odd (E = 69)...
{               # ...and execute this block if it is:
    ~           # dump the remaining lines (of which the should be only one) on the stack
    . ,         # calculate the length of the last line...
    [ { 26 rand 65 + } * ]  # ...make an array of that many random letters...
    :K          # ...and assign it to K
    ]           # collect all the lines, including K, back into an array
} *

# ENCRYPTION / DECRYPTION ROUTINE:
zip             # transpose the array of 2 n-char strings into n 2-char strings...
{               # ...and execute this block for each 2-char string:
    {-} *       # subtract the second char code from the first
    ~ )         # negate the result (using the two's complement trick -x = ~x+1)
    26 % 65 +   # reduce modulo 26 and add 65 = A
} %

# OUTPUT:
K ] n*         # join the result and K (if defined) with a newline, stringifying them

Ruby (200 185)
sample runs + wc:
$ ruby onetimepad.rb
ENCODE
ANOTHERTESTINPUTZZZ
ZYCLGHDWLDASFUTHWKC
BPMIBXOXTPTQIVBMDPX
$ ruby onetimepad.rb
DECODE
ZYCLGHDWLDASFUTHWKC
BPMIBXOXTPTQIVBMDPX
ANOTHERTESTINPUTZZZ
$ wc onetimepad.rb
       4       7     185 onetimepad.rb

def f;gets.scan(/./).map{|b|b.ord-65};end
s=->a{a.map{|b|(b+65).chr}*''}
r=->b,a,o{s[a.zip(b).map{|a,b|(a.send o,b)%26}]}
puts(gets=~/^D/?r[f,f,:+]:[s[k=(p=f).map{rand 26}],r[k,p,:-]])

s[k=(p=f).map{rand 26}],r[k,p,:-] should be written s[k=f.map{rand 26}],r[k,$_,:-]

@Hauleth no that doesn't work, as $_ is just the last line read by gets. f also does .scan(/./).map{|b|b.ord-65} after reading a line.

APL (Dyalog Unicode), 46 bytes
⎕A[26|{'N'∊⍞:⍉x,⍪(⎕A⍳w)+x←26?⍨⍴w←⍞⋄-⌿⎕A⍳↑⍞⍞}1]

Try it online!
The current full program is the result of a 2hr long session at The APL Orchard., with a lot of golfing input from Adám (-13 bytes!).
Requires ⎕IO←0 (0-indexing).
Explanation
⎕A[26|{'N'∊⍞:⍉x,⍪(⎕A⍳w)+x←26?⍨⍴w←⍞⋄-⌿⎕A⍳↑⍞⍞}1]
      {                                    }1  inner fn(called with junk param)
           ⍞                                   first input
       'N'∊                                    is 'N' present in it?
            :⍉x,⍪(⎕A⍳w)+x←26?⍨⍴w←⍞             if so, eNcrypt:
                               w←⍞              store message in w
                          26?⍨⍴                 generate 26 random numbers,
                        x←                      store in x
                 (⎕A⍳w)+                        add that to the indices in the alphabet
                ⍪                               table them
              x,                                join with the random numbers
             ⍉                                  transpose to get key and encrypted value
                                  ⋄-⌿⎕A⍳↑⍞⍞    else, decrypt:
                                         ⍞⍞     input key and value
                                        ↑       convert to matrix
                                     ⎕A⍳        get the indices of both in the alphabet
                                   -⌿           difference of all columns
   26|                                          mod the result of the inner fn.
  [                                          ] index the result of the program in
⎕A                                             the capitalized alphabet.

Haskell, 203 characters
import Random
main=newStdGen>>=interact.(unlines.).(.lines).f.randomRs('A','Z')
f k['E':_,x]=[z const k x,z(e(+))k x]
f _[_,k,x]=[z(e(-))k x]
e(%)k x=toEnum$65+o x%o k`mod`26
o c=fromEnum c-65;z=zipWith

Example:
$ runghc OneTimePad.hs <<< $'ENCRYPT\nHELLOWORLD'
QMNQKGFZFD
XQYBYCTQQG
$ runghc OneTimePad.hs <<< $'DECRYPT\nQMNQKGFZFD\nXQYBYCTQQG'
HELLOWORLD

Perl, 220 171 characters
if(<>=~/D/){$_=<>;$w=<>;print chr((ord(substr$w,$i++,1)-ord$1)%26+65)while/(.)/g}else{$_=<>;$c.=chr((ord($1)-65+($i=rand(26)))%26+65),print chr$i+65while/(.)/g;print$/.$c}

Sample Run:
ENCRYPT
HELLO
CCTKK
JGEVY

DECRYPT
CCTKK
JGEVY
HELLO

Note: at least when I run it, "Press any key to continue..." is appended to the end of the last output. I hope this is ok, because it isn't part of the program. If not, I can make it so it appears on the next line.
This is my first real program in Perl, and my first golf ever, so I would really appreciate tips. Also, I found /(.)/g on the internet, but I have no idea how it works (is it a regular expression? I haven't learnt those yet). Can somebody explain it to me?
EDIT: Thanks to Ilmari Karonen for helping me out with the regexps, I used my new knowledge to save 7 characters!
Expanded, slightly legible version:
if(<>=~/D/){
    $_=<>;
    $w=<>;
    print chr((ord(substr$w,$i++,1)-ord$1)%26+65)while/(.)/g
}
else{
    $_=<>;
    $c.=chr((ord($1)-65+($i=rand(26)))%26+65),print chr$i+65while/(.)/g;
    print$/.$c
}

Yes, /(.)/g is a regexp. You'll definitely want to learn those if you're going to play Perl golf. http://perldoc.perl.org/perlre.html is not a bad starting place.

Python - 304 295
import random
r=raw_input
R=lambda s:range(len(s))
o=lambda c:ord(c)-65
j=''.join
if r()[0]=='D':
 s=r()
 d=r()
 print j(chr((o(s[i])-o(d[i]))%26+65)for i in R(s))
else:
 s=r()
 d=[random.randint(0,26)for i in R(s)]
 print j(chr((o(s[i])+d[i])%26+65)for i in R(s))
 print j(chr(n+65)for n in d)

I believe that this meets the specs exactly (Including the '>' at the start of the input prompts.) It does not validate input, so I think that it will just produce garbage output if you give it characters outside of [A-Z]. It also only checks the first letter of the input command. Anything starting with D will result in a decryption and anything else at all will result in an encryption.

I didn't expect you to print the >, I was just using it to demonstrate which lines were output. You don't have to implement those.

Ok, cool, 9 fewer characters then.

C++ - 220 241 chars, 4 lines
#include<cstdlib>
#include<cstdio>
#define a scanf("%s"
char i,s[99],t[99];int main(){a,t);a,s);if(t[0]>68){for(;s[i];++i)s[i]=(s[i]+(t[i]=rand()%26+65))%26+65;puts(t);}else for(a,t);s[i];++i){s[i]=65+t[i]-s[i];if(s[i]<65)s[i]+=26;}puts(s);}

Edit 1- The MSVS standard library seems to include a lot of unnecessary files which meant that ios had all the includes that I needed but this didn't work with other compilers.  Changed ios for the actual files that the functions needed appear in cstdlib and cstdio.  Thanks to Ilmari Karonen for pointing this out.

Doesn't compile for me: g++ otp.cpp says otp.cpp: In function ‘int main()’: otp.cpp:3: error: ‘scanf’ was not declared in this scope otp.cpp:3: error: ‘rand’ was not declared in this scope otp.cpp:3: error: ‘puts’ was not declared in this scope otp.cpp:3: error: ‘puts’ was not declared in this scope

Huh, that's strange, I use visual studio.  It must be non-standard for  to have <conio.h> and <stdio.h> in it's includes.  I assumed the headers always included the same files on different implementations.  I'll look into it later, Thanks.

Python - 270
import random
i=raw_input
m=i()
a=i()
r=range(len(a))
o=ord
j=''.join
if m=='ENCRYPT':
  k=j(chr(65+random.randint(0,25)) for x in r)
  R=k+"\n"+j(chr((o(a[x])+o(k[x]))%26+65) for x in r)
elif m=='DECRYPT':
  k=i()
  R=j(chr((o(k[x])-o(a[x]))%26+65) for x in r)
print R

Sample output:
$ python onetimepad.py
ENCRYPT
HELLOWORLD
UXCYNPXNNV
BBNJBLLEYY
$ python onetimepad.py
DECRYPT
UXCYNPXNNV
BBNJBLLEYY
HELLOWORLD

Character count:
$ wc -c onetimepad.py
270 onetimepad.py

J : 94 bytes
3 :0]1
c=:(26&|@)(&.(65-~a.&i.))
r=:1!:1@1:
((],:+c)[:u:65+[:?26$~#)@r`(r-c r)@.('D'={.)r 1
)

All necessary white space counted.
Commented version:
3 :0]1                                          NB. Make a function and call it
c=:(26&|@)(&.(65-~a.&i.))                       NB. Adverb for operating on the alphabet
                                                NB. (used for adding and subtracting the pad)
r=:1!:1@1:                                      NB. Read input line and decide (right to left)
((],:+c)[:u:65+[:?26$~#)@r   ` (r-c r)            @. ('D'={.)r 1
NB. Encryption (ger    0)    | Decryption (ger 1)| Agenda
NB. pad,:(crypt=:plain + pad)| crypt - pad       | If D is first input, do (ger 1), else do (ger 0)
)

C# (445 416)
Forgot about Aggregate. Cut off a good bit.
Somewhat golfed:
namespace G {
using System;
using System.Linq;
using x = System.Console;
class P {
    static void Main() {
        string p = "", c = "", k = "";
        Random r = new Random();
        int i = 0;
        if (x.ReadLine()[0] == 'E') {
            p = x.ReadLine();
            k=p.Aggregate(k,(l,_)=>l+(char)r.Next(65,90));
            c=p.Aggregate(c,(m,l)=>m+(char)((l+k[i++])%26+65));
            x.WriteLine(k + "\n" + c);
        } else {
            k = x.ReadLine();
            c = x.ReadLine();
            p=c.Aggregate(p,(l,a)=>l+(char)((a-k[i++]+26)%26+65));
            x.WriteLine(p);
        }
    }
}

}
Golfed:
namespace G{using System;using System.Linq;using x=System.Console;class P{static void Main(){string p="",c="",k="";Random r=new Random();int i=0;if (x.ReadLine()[0]=='E'){p=x.ReadLine();k=p.Aggregate(k,(l,_)=>l+(char)r.Next(65,90));c=p.Aggregate(c,(m,l)=>m+(char)((l+k[i++])%26+65));x.WriteLine(k+"\n"+c);}else{k=x.ReadLine();c=x.ReadLine();p=c.Aggregate(p,(l,a)=>l+(char)((a-k[i++]+26)%26+65));x.WriteLine(p);}}}}

JavaScript 239
var F=String.fromCharCode
function R(l){var k='';while(l--)k+=F(~~(Math.random()*26)+65);return k}
function X(s,k,d){var o='',i=0,a,b,c
while(i<s.length)a=s.charCodeAt(i)-65,b=k.charCodeAt(i++)-65,c=d?26+(a-b):a+b,o+=F((c%26)+65)
return o}

Usage:
var str = "HELLOWORLD";
var key = R(str.length);
var enc = X(str, key, false);
console.log(enc);
console.log(X(enc,key, true));

Ruby - 184 179 177 chars
def g;gets.scan(/./).map{|c|c.ord-65}end
m,=g
k=(s=g).map{rand 26}
m==4?(puts k.map{|c|(c+65).chr}*'';y=:+):(k,s=s,g)
puts s.zip(k).map{|c,o|(c.send(y||:-,o).to_i%26+65).chr}*''

Run it like this: $ ruby pad-lock.rb
Here is the ungolfed version if anyone is interested (it's not quite up to date with the golfed one though)
def prompt
    gets.scan(/./).map{ |c|c.ord - 65 }
end

mode = prompt[0]
operator = :-
secret = prompt
key = secret.map { |char| rand(26) }

if mode == 4 # the letter E, or ENCRYPT
    key.map { |char| print (char + 65).chr }
    puts
    operator = :+
else
    # make the old secret the new key,
    # and get a new secret (that has been encrypted)
    key, secret = secret, prompt
end

chars = secret.zip(key).map do |secret_char, key_char|

    # if mode == 4 (E) then add, otherwise subtract
    i = secret_char.send(operator, key_char).to_i

    ((i % 26) + 65).chr
end

puts chars.join("")

C (159 + 11 for compiler flags)
Golfed:

d(a,b){return(a+b+26)%26+65;}a;char s[999],b,*c=s-1;main(){g;a=*s-69;g;while(*++c)a?b=-*c,*c=getchar():putchar(b=rand()%26+65),*c=d(*c,b);a||puts("");puts(s);}

Ungolfed:

d(a,b){
    //*a = (*a + b - 2*65 + 26) % 26 + 65;
    return (a + b + 26) % 26 + 65;
}
a; char s[999], b, *c = s-1;
main(){
    gets(s);
    a = *s - 69; // -1 if decrypt 0 if encrypt
    gets(s);
    while(*++c){
        if(!a)
            putchar(b = rand() % 26 + 65); // 'A'
        else
            b = -*c, *c = getchar();
        *c = d(*c,b);
    }
    if(!a) puts("");
    puts(s);
}

Compile with -Dg=gets(s).
Example:
$./onetimepad
ENCRYPT
FOOBAR
>PHQGHU
>UVEHHL
$./onetimepad
DECRYPT
PHQGHU
UVEHHL
>FOOBAR

I get the same key every time I run it--there is no randomness.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

authors: Данаил Димитров

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Encode an image inside of the source
The golf challenge is to encode and compress the following image inside a source file.

To do this you need to write 3 functions: red, green, and blue which accept x/y coordinates of the image and return the corresponding R/G/B pixel value between 0-255.
Here is the C/C++ test code:
#include <stdio.h>
#include "your_file"
int main() {
  int x, y;
  for(y = 0; y < 32; ++y)
  for(x = 0; x < 32; ++x)
    printf("%i %i %i\n", red(x, y), blue(x, y), green(x, y));
}

And the output: http://pastebin.com/A770ckxL (you can use this to generate your image data)
Rules & details:

This is a golf
Only your code/file is golfed - the test code is separate
The character set used is ASCII, however control characters in strings may only be used if escaped (like '\n' and '\r', etc)
Everything must be contained inside the source - no file loading
Your output must match the example output. This means loseless compression.

Languages:
The problem was written with C/C++ in mind, but I'm removing those restrictions. With that said, I'll still recommend using them.

If there is no specific reason to do so, fixing a question to a specific language is highly discouraged. What is the reason why one must not use other languages?

@FUZxxl I was afraid other languages would be less interesting and use something like Unicode hacks or base 64. If anyone has a great solution that requires another language then I'll gladly update the rules.

If a solution is less interesting, don't vote it up. Forbidding "lame" solutions by exclusing languages is overkill.

If you've already limited the character set to ASCII (which I consider absolutely ok), how could we use Unicode hacks? As for base 64, you can do that inside standard C as well as any other language, it only different amounts of wrapper code. — But I like the task.

Alright, I removed the restriction but left the suggestion.

Hmm, what about the ASCII control characters 0-31 (and 127)? Technically, they're part of ASCII, but are they allowed? And if not, I hope an exception is at least made for the LF character (10), and maybe CR (13) and TAB (9) too?

@IlmariKaronen I updated the question.

Um... so, reading your new version literally, all solutions have to be on one line, because unescaped line feeds are not allowed. Is that really what you intend?

C, 796 754 712 703 692 685 682 670 666 662 656 648 chars
Changelog:

754->712: Added return to the #define, replacing if with ? statements (thanks @FUZxxl), removing int from the functions parameter list.
712->703: Shameless copy from bunnit again :) Moved the whole image creation into the #define
703->692: Merged p[] and h[], some more ?: improvements
692->685: Incrementing b so i isn't needed anymore. m=b instead of m=11 and n<2e3 instead of i<356 - these are close to undefined behaviour/memory corruption, but it seems I'm lucky :)
685->682: k is now (32,16,8,4,2,1,0) instead of (5,4,3,2,1,0). Gotcha, D C ;)
682->670: Split p[] and h[], converted h[] to a char* - awwww, there's a sleepy kitty in it ^<+_=>-
670->666: while => for, l=l*2+... => l+=l+...
666->662: m=m>9?... => c[n++]=m>9?...
662->656: Reversed bit order in b[], so we can map to 64-127 instead of 0-63 and don't need bit index k anymore. Thanks @Piotr Tarsa. Replaced ?: (GCC extension) with ||. Thanks @JamesB
656->648: Shameless copy from Shelwien :) (multi-character constants for p[])

Image is converted to a Base64-like string (ASCII 37-100), using huffman coding to encode colors 0-9 using 3-6 bits and a special color 10 (pixel is same as previous one) using only 1 bit.
#define P (x,y){for(;n<2e3;j/=2){j>1||(j=*b+++27);l+=l+(j&1);for(m=0;m<11;m++)l-h[m]+32||(c[n++]=m>9?c[n-1]:m,l=0,m=b);}return 255&p[c[x+y*32]]
char*h="$^<+_=>-,* ",*b="F0(%A=A=%SE&?AEVF1E01IN8X&WA=%S+E+A-(,+IZZM&=%]U5;SK;cM84%WE*cAZ7dJT3R.H1I2@;a^/2DIK&=&>^X/2U*0%'0E+;VC<-0c>&YU'%],;]70R=.[1U4EZ:Y=6[0WU4%SQARE0=-XDcXd_WW*UAF&cFZJJ0EV*(a(P05S3IXA>51cH:S5SAE6+W%/[]7SF(153UM]4U()(53DA+J:]&5+5KX,L6>*4I,/UMBcML9WKLa9%UYIHKWW(9-*):(-ZW(9%T'N&9;C,C/Ea/Y7(JJ\\6CD9E,2%J*,ac]NIW8(M=VFac)/^)?IS-;W&45^%*N7>V,,C-4N35FMQaF,EaWX&*EJ4'";p[]={0,'R@+','aXL',7783255,'4k`',16354410,'NNv',5295994,4671418,9975021},c[1024],j,l,m,n;red P;}blue P>>16;}green P>>8;}

Copied two things from bunnit's answer, the #define and the whole image being decoded completely every time red/green/blue are called. There's some room for additional improvement, so expect some updates :) I'm not sure about code compliance, used GCC 4.6.1 to compile and test.
Compression-wise, I think arithmetic coding would help as the distribution is pretty skewed, but maybe code overhead would be too heavy in this case. LZW also should do a very good job. Colors are quite local, so adaptive coding might be an idea.
More readable 754 character version with some comments:
#define P 255&p[c[x+y*32]]
// Base64 coded image bitstream, ASCII 37-100
// Huffman codes: 100, 111110, 11100, 1011, 111111, 11101, 11110, 1101, 1100, 1010, 0
char b[]="FYU%3+3+%B&E;3&HF1&Y1.JWXE83+%B=&=3)U]=.PP*E+%,('?B>?D*Wa%8&MD3P7dNbARIV1.Q[?4L9Qc.>E+EKLX9Q(MY%5Y&=?HC_)YDKE0(5%,]?,7YR+I@1(a&PO0+G@Y8(a%B23R&Y+)XcDXd<88M(3FEDFPNNY&HMU4UZY'BA.X3K'1DVOB'B3&G=8%9@,7BFU1'A(*,a(U-U'Ac3=NO,E'='>X]^GKMa.]9(*SD*^/8>^4/%(0.V>88U/)M-OU)P8U/%b5JE/?C]C9&4907UNN`GCc/&]Q%NM]4D,J.8WU*+HF4D-9L-;.B)?8Ea'L%MJ7KH]]C)aJA'F*24F]&48XEM&Na5";
// Colors, order GBR (one char shorter than all the others)
p[]={0,5390379,6379596,7783255,3435360,16354410,5131894,5295994,4671418,9975021};
// Huffman codes for colors 0-10
h[]={4,62,28,11,63,29,30,13,12,10,0};
// Array for image data
c[1024];
i,j,k,l,m,n;
red(int x,int y){
  while(i<356){
    k--;
    if (k<0) {
      j=b[i++]-37;
      k=5;
    }
    l*=2;
    if (j&(1<<k)) l++;
    for(m=0;m<11;m++){
      if(l==h[m]){
        if (m>9) m=c[n-1];
        c[n++]=m;
        l=0;
        m=12;
      }
    }
  }
  return P;
}
blue(int x,int y){return P>>16;}
green(int x,int y){return P>>8;}

Very nice, can't believe I didn't think about using base 64.  I think you can still save quite a few characters though, especially in that loop.  Works fine in VS2008 btw.

I think you can remove that int's from the parameter lists to remove some more bytes.

How about
m=m>9?c[n-1]:m;
for
if(m>9)m=c[n-1];?

And also: for
if(k<0){j=b[i++]-37;k=5;} why not
k>=0?:(j=b[i++]-37,k=5);? (This code uses a C extension of gcc, x=a?:b is the same as x=a?a:b, with the difference that a is evaluated only once.

red(x,y){while(i<356){--k>=0?:(j=b[i++]-37,k=5);l*=2;if(j&(1<<k))l++;for(m=0;m<11;m++)l!=h[m]?:(m=m<=9?:c[n-1],c[n++]=m,l=0,m=12);}return P;}

instead of: red(int x,int y){while(i<356){k--;if(k<0){j=b[i++]-37;k=5;}l*=2;if(j&(1<<k))l++;for(m=0;m<11;m++){if(l==h[m]){if(m>9)m=c[n-1];c[n++]=m;l=0;m=11;}}}return P;}

@FUZxxl: Thanks! A part of your last suggestion didn't work (the modified m loop), but everything else did.

for color numbering you can use hex value, and shorten your code even more

@Gajet: Unfortunately, I can't, because the hexadecimal prefix in C is 2 chars long - 16354410 is as long as 0xF98C6A.

Python (684 592 characters)
red,blue,green=[lambda x,y,i=i:[15570996,2839104,7010700,5732035,6304875,0,12207943,8016079,7753294,5005656][int('eJxtkgGSxSAIQ6+kaLTe/2JLImj7Z9MZ6/gMIgjAzMbVWisGySRNm2ut5Hhx/2M0JMfHH5PWwo9x4mNO8pb6JkFM3hpqrR4+qY6eVK1mjlsFeSOBjPyCMy3348aXVRtq9X8czovMIwA5FeXKtGOcvfcf/lbvyW0n2BTOh122HiIH0g/uNrx47zupzMxuuTv808pZd3K7deJ/+PiH61AztmaNwPAsOnNGYovWIxswRill6vnAL4HgxDF17jFcjwRk/5b3Q1x1flLI9n64CIci8bmQe7NL8XoKliu+Jk/AR9rnjkwAYaDka8OXu/a+5NvvNzkcmqifL47H04kAz9M+9slKkDMGuOHi5PR7GZwv7MeApkz5JOSPHFVW3QTbzDJtzDIczkuWjeupLbckLyU5/gByftMg'.decode('base64').decode('zip')[32*y+x])]>>i&255 for i in 16,8,0]

Since this challenge is now open to all, why not! It's the familiar zlib -> base64 encoding route, so I apologize for that. Hopefully an entry with some semblance of ingenuity will be shorter!
Here's a test snippet analogous to the original:
for y in range(32):
    for x in range(32):
        print red(x,y), blue(x,y), green(x,y)

You should try adding a special color to repeat the previous pixel value, too. 588 chars base64 is much larger than the string in my answer (365 chars) and although zLib is overkill here, it should give a similar result, so around 500 chars total should be possible this way.

C++, 631 chars; C - 613
A base-92 unary mtf coder, C++, 631 chars:
#define A(Z)int Z(int X,int Y){char*s="xdGe*V+KHSBBGM`'WcN^NAw[,;ZQ@bbZVjCyMww=71xK1)zn>]8b#3&PX>cyqy@6iL?68nF]k?bv/,Q`{i)n[2Df1zR}w0yIez+%^M)Diye{TC]dEY\\0,dU]s'0Z?+bo;7;$c~W;tvFl%2ruqWk$Rj0N[uP)fSjk?Tnpn_:7?`VbJ%r@7*MQDFCDo3)l#ln<kuRzzHTwCg&gYgSXtv\\m_Eb}zRK7JK<AZzOe}UX{Crk)SyBn;;gdDv=.j*O{^/q6)`lHm*YYrdM/O8dg{sKW#B3BLMiI8@-Zo-EsgE.R#viYL$-<EU*~u5pe$r:`b)^dgXOJtf4";int*v,B=92,R=1,C=0,w[]={0,16354410,4671418,'aXL',7783255,5295994,'R@+','4k`',9975021,'NNv'};for(X+=Y*32+1;X--;)for(v=w;;){for(Y=*v++;R<B*B*B;C=C%R*B+*s++-35)R*=B;if(R/=2,C>=R){for(C-=R;--v>w;*v=v[-1]);*v=Y;break;}}return 255&Y
A(red);}A(blue)>>16;}A(green)>>8;}

And the C version of above (613 chars):
#define A (X,Y){char*s="xdGe*V+KHSBBGM`'WcN^NAw[,;ZQ@bbZVjCyMww=71xK1)zn>]8b#3&PX>cyqy@6iL?68nF]k?bv/,Q`{i)n[2Df1zR}w0yIez+%^M)Diye{TC]dEY\\0,dU]s'0Z?+bo;7;$c~W;tvFl%2ruqWk$Rj0N[uP)fSjk?Tnpn_:7?`VbJ%r@7*MQDFCDo3)l#ln<kuRzzHTwCg&gYgSXtv\\m_Eb}zRK7JK<AZzOe}UX{Crk)SyBn;;gdDv=.j*O{^/q6)`lHm*YYrdM/O8dg{sKW#B3BLMiI8@-Zo-EsgE.R#viYL$-<EU*~u5pe$r:`b)^dgXOJtf4";int*v,B=92,R=1,C=0,w[]={0,16354410,4671418,'aXL',7783255,5295994,'R@+','4k`',9975021,'NNv'};for(X+=Y*32+1;X--;)for(v=w;;){for(Y=*v++;R<B*B*B;C=C%R*B+*s++-35)R*=B;if(R/=2,C>=R){for(C-=R;--v>w;*v=v[-1]);*v=Y;break;}}return 255&Y
red A;}blue A>>16;}green A>>8;}

Just to include an entry with base-95 data and arithmetic coding + adaptive statistical model.
schnaader's code uses ~438 chars for data, and mine only 318 (311 w/o masking).
But as expected, arithmetic coding is too complicated for a small sample like this.
(This is 844 chars)
char* q="q^<A\">7T~pUN1 adz824K$5a>C@kC8<;3DlnF!z8@nD|9D(OpBdE#C7{yDaz9s;{gF[Dxad'[oyg\\,j69MGuFcka?LClkYFh=:q\\\\W(*zhf:x)`O7ZWKLPJsP&wd?cEu9hj 6(lg0wt\\g[Wn:5l]}_NUmgs]-&Hs'IT[ Z2+oS^=lwO(FEYWgtx),)>kjJSIP#Y?&.tx-3xxuqgrI2/m~fw \\?~SV={EL2FVrDD=1/^<r*2{{mIukR:]Fy=Bl.'pLz?*2a? #=b>n]F~99Rt?6&*;%d7Uh3SpLjI)_abGG$t~m{N=ino@N:";
#define I int
#define F(N) for(i=0;i<N;i++)
#define Z C=(C%T)*B+(*q++)-32
enum{B=95,H=1024,T=B*B*B};I p[B],v[B+H],n=3,*m=&v[B],R=T*B,C,i,j,y,c,x,w;void D(I P){w=(R>>11)*P;(y=C>=w)?R-=w,C-=w:R=w;while(R<T)R*=B,Z;}struct u{u(){F(4)Z;F(B)p[i]=H,v[i]=0;F(H){v[0]=m[i-1];v[1]=m[i-32];j=i;F(n){I&P=p[i];D(P);if(y){P-=P>>4;c=v[i];goto t;}else P+=H+H-P>>4;}c<<=7;for(x=-255;x<0;x+=x+y)D(H);v[n++]=c=x;t:m[i=j]=c;}}}d;I red(I x,I y,I z=0){return m[y*32+x]>>z&255;}
#define blue(x,y) red(x,y,8)
#define green(x,y) red(x,y,16)

Tests (from earlier base-96 version):
http://codepad.org/qrwuV3Oy
http://ideone.com/ATngC
Somehow SO eats 7F codes, so I had to update it to base=95

C++ - 1525 1004 964 chars
#define e (int x,int y){for(i=g=0;i<702;i=i+2)for(j=48;j<d[i];++j)c[g++]=d[i+1]-48;return 255&z[c[x+y*32]]
int i,g,j,z[]={0,7010700,12207943,5005656,5732035,8016079,2839104,6304875,15570996,7753294},c[1024];
char*d="3031;23322337261524453223310625132101214103453101233722172643310323342102521229492333210352112241036141014821042552621241014161016141024121022103210151015104526211034361034726510352625107441:530855425201511551045378554>55755312410242035201510528725212044451015411032:73135216561321012171017101725313581125152572531358122415257257110213310131231422022172025105110315322103210623815203110113053521053223817506920721013361322282530991062101213361322282520491049682224133614121028101510291029;812341023342835694810582018841018356978194810842835193329781019482410542835192310193668399428454319362928102829843845331019263028101330441014382035104369285338101810284536334910291018534820283546891019102943883536";
int red e>>16;}
int blue e>>8;}
int green e;}

Created an array z which stores all of the possible colours as a single integer.(r<<16 | g<<8 | b).
Created an array d which stores {amount, value}, the value is the position in the array z, the amount is the number of consecutive pixels with that value.(i.e 3,0, means colout t[0] appears the next 3 pixels.
The actual array of pixels(c) is then calculated every time red is called.
The value in the array is then right shifted and ANDed as necessary to get the correct component.
I could probably save a few more characters(~50) by taking more patterns out of the array as defines.
Edit 1 - changed the d array for a char array with each value offset by 48, which means I can represent it as a string saving a load of commas.
Edit 2 - Took a larger portion of the functions out in the define statement.

Why don't you use C? In C, it is possible to remove the type-name from a declaratrion if it is int (so int f(int x,int y) becomes f(x,y).

@FUzxxl, yes C will almost always be shorter than C++ but I don't really use C on a day to day basis and don't really know all of it's nuances that can be used to reduce the length.  I'm not bothered by trying to win anyway, I just try to beat any other C++ answers.

Javascript, 696 694 chars
Thanks to schnaader for 696 -> 694.
I figured a different encoding format, which essentially is Run-length encoding with a color lookup table. It works quite nice, because there are less than 16 colors and they apear less that 16 times in a row; so every pixel definition including length fits into one byte. I put the color in the high part of the byte and the count in the low part.
In the end, the base64 string turned out to be longer than I had expected (472 chars), but the decoding program is really short.
for(b=i=a=[];a&15||(a=atob("AxMrMyIzJxYlRDUiMwEmFSMBIUEBQzUBITMnEidGMwEjMyQBUhIi
SSkzIwFTEiFCAWNBAUEoASRVYhJCAUFhAWFBAUIhASIBIwFRAVEBVGISAUNjAUMnVgFTYlIBRxRaA1hF
UgJREVUBVHNYRV51VRNCAUICUwJRASV4UhICRFQBURQBI3oTUxJWFiMBIXEBcQFxUhNTGCEVJXVSE1MY
IhQldVIXARIzATEhEyQCInECUgEVARM1IgEjASaDUQITAREDNSUBNSKDcQWWAicBMWMxIoJSA5kBJgEh
MWMxIoJSApQBlIYiQjFjQSEBggFRAZIBkoshQwEyQ4JTloQBhQKBSAGBU5aHkYQBSIJTkTOShwGRhEIB
RYJTkTIBkWOGk0mCVDSRY5KCAYKSSINUMwGRYgOCATEDRAFBgwJTATSWgjWDAYEBglRjM5QBkgGBNYQC
glNkmAGRAZI0iFNjAQ==").charCodeAt(i++));b.push([0,16354410,4671418,6379596,77832
55,5295994,5390379,3435360,9975021,5131894][a-- >>4]));green=(red=function(c,d){
return b[32*d+c]>>this&255}).bind(16);blue=red.bind(8)

Note: I split up the code to have a little readability. It needs to be on one line to run.
Test code:
for(var y = 0; y < 32; ++y) {
    for(var x = 0; x < 32; ++x) {
        console.log(red(x, y), green(x, y), blue(x, y));
    }
}

I think the example result is actually the output of red, green, blue (not red, blue, green like in the original test code); it works for me like that anyway.

Try to change the palette array to [0,16354410,4671418,6379596,7783255,5295994,5390379,3435360,9975021,5131894] - this saves 1 character and is GBR order instead of RGB.

@schnaader Thanks. I love those micro-optimizations :-) Edit: It even saved 2 chars because I used blue two times in my orignial source

C++, 1357 chars
int i,j,C[]={0,0,0,106,249,140,186,71,71,76,97,88,87,118,195,122,80,207,43,82,64,96,52,107,237,152,52,118,78,78},E[]={30,31,112,33,22,33,72,61,52,44,53,22,33,10,62,51,32,10,12,14,10,34,53,10,12,33,72,21,72,64,33,10,32,33,42,10,25,21,22,94,92,33,32,10,35,21,12,24,10,36,14,10,14,82,10,42,55,26,21,24,10,14,16,10,16,14,10,24,12,10,22,10,32,10,15,10,15,10,45,26,21,10,34,36,10,34,72,65,10,35,26,25,10,74,41,105,30,85,54,25,20,15,11,55,10,45,37,85,54,145,57,55,31,24,10,24,20,35,20,15,10,52,87,25,21,20,44,45,10,15,41,10,32,107,31,35,21,65,61,32,10,12,17,10,17,10,17,25,31,35,81,12,51,52,57,25,31,35,81,22,41,52,57,25,71,10,21,33,10,13,12,31,42,20,22,17,20,25,10,51,10,31,53,22,10,32,10,62,38,15,20,31,10,11,30,53,52,10,53,22,38,17,50,69,20,72,10,13,36,13,22,28,25,30,99,10,62,10,12,13,36,13,22,28,25,20,49,10,49,68,22,24,13,36,14,12,10,28,10,15,10,29,10,29,118,12,34,10,23,34,28,35,69,48,10,58,20,18,84,10,18,35,69,78,19,48,10,84,28,35,19,33,29,78,10,19,48,24,10,54,28,35,19,23,10,19,36,68,39,94,28,45,43,19,36,29,28,10,28,29,84,38,45,33,10,19,26,30,28,10,13,30,44,10,14,38,20,35,10,43,69,28,53,38,10,18,10,28,45,36,33,49,10,29,10,18,53,48,20,28,35,46,89,10,19,10,29,43,88,35,36,10};int*Q(int n){for(i=0;1;i++){for(j=0;j<E[i]/10;j++){if(!n)return&C[E[i]%10*3];n--;}}}
#define red(x,y) Q(x+32*y)[0]
#define blue(x,y) Q(x+32*y)[1]
#define green(x,y) Q(x+32*y)[2]

Deobfuscated a bit:
int C[]={0,0,0,106,249,140,186,71,71,76,97,88,87,118,195,122,80,207,43,82,64,96,52,107,237,152,52,118,78,78},
int E[]={30,31,112,33,22,33,72,61,52,44,53,22,33,10,62,51,32,10,12,14,10,34,53,10,12,33,72,21,72,64,33,10,32,33,42,10,25,21,22,94,92,33,32,10,35,21,12,24,10,36,14,10,14,82,10,42,55,26,21,24,10,14,16,10,16,14,10,24,12,10,22,10,32,10,15,10,15,10,45,26,21,10,34,36,10,34,72,65,10,35,26,25,10,74,41,105,30,85,54,25,20,15,11,55,10,45,37,85,54,145,57,55,31,24,10,24,20,35,20,15,10,52,87,25,21,20,44,45,10,15,41,10,32,107,31,35,21,65,61,32,10,12,17,10,17,10,17,25,31,35,81,12,51,52,57,25,31,35,81,22,41,52,57,25,71,10,21,33,10,13,12,31,42,20,22,17,20,25,10,51,10,31,53,22,10,32,10,62,38,15,20,31,10,11,30,53,52,10,53,22,38,17,50,69,20,72,10,13,36,13,22,28,25,30,99,10,62,10,12,13,36,13,22,28,25,20,49,10,49,68,22,24,13,36,14,12,10,28,10,15,10,29,10,29,118,12,34,10,23,34,28,35,69,48,10,58,20,18,84,10,18,35,69,78,19,48,10,84,28,35,19,33,29,78,10,19,48,24,10,54,28,35,19,23,10,19,36,68,39,94,28,45,43,19,36,29,28,10,28,29,84,38,45,33,10,19,26,30,28,10,13,30,44,10,14,38,20,35,10,43,69,28,53,38,10,18,10,28,45,36,33,49,10,29,10,18,53,48,20,28,35,46,89,10,19,10,29,43,88,35,36,10};
int*Q(int n){
  for(int i=0;1;i++){
    for(int j=0;j<E[i]/10;j++){
      if(!n)return&C[E[i]%10*3];
      n--;
    }
  }
}
#define red(x,y) Q(x+32*y)[0]
#define blue(x,y) Q(x+32*y)[1]
#define green(x,y) Q(x+32*y)[2]

C contains the RGB values for the ten distinct colors of the image.  E contains the data for the picture, where each element E[i] encodes both a repeat count E[i]/10 and a color index E[i]%10.

+1 You could shave a few characters off in the loop: http://pastebin.com/2UY8H2qt

If you rebrand your solution as C (no code changes required) and turn the define's into functions whithout type names like int red(x,y){R Q(x+32*y)[0]}(only #define return`), then you might be able to shave of more characters.

Somehow, this is cheating, since red, blue and green are not functions but macros.

This implements a function and is shorter (1339 bytes). Please notice, that this program is probably only valid in plain old C: http://hpaste.org/65584

I removed all type information from the source. It is still valid C.

C (gcc), 602 584 bytes
-18 bytes thanks to ceilingcat.
X[1024],*i,r,w,*I;
#define u(d)(x,y){i=X;for(I=L"56s-8-8_TKCL-8!UJ7!#%!9L!#8_,_W8!78A!0,-us87!:,#/!;%!%i!AN1,/!%'!'%!/#!-!7!&!&!D1,!9;!9_X!:10!a@v&5lM0+&\"N!D<lMvNPN6/!/+:+&!Kn0,+CD!&@!7x(6:,XT7!#(!(!(06:h#JKP06:h-@KP0^!,8!$#6A+-(+0!J!6L-!7!U=&+6!\"5LK!L-=(I\\+_!$;$-305z!U!#$;$-30+H!H[-/$;%#!3!&!4!4y3#9!.93:\\G!Q+)k!):\\e*G!k3:*84e!*G/!M3:*.!*;[>u3DB*;43!34k=D8!*153!$5C!%=+:!B\\3L=!)!3D;8H!4!)LG+3:Ep!*!4Bo:;!";w=*I-33,*I++;)for(r=w/10+1;r--;*i++=L"\0\x6a8cf9\xba4747\x4c5861\x57c376\x7acf50\x2b4052\x606b34\xed3498\x764e4e"[w%10]>>d&255);x=X[y*32+x];}
red u(16)green u(8)blue u(0)

Try it online!

Python 3 (589 characters)
import base64,zlib
red,blue,green=(lambda x,y,i=i:b'\xed\x984+R@j\xf9\x8cWv\xc3`4k\0\0\0\xbaGGzP\xcfvNNLaX'[zlib.decompress(base64.decodebytes(b'eJxtkgGSxSAIQxWN1vtfeEkEbf9sOmMdn0EEAZjZuFprxSCZpGlzrZUcL+5/jIbk+Phj0lr4MU58zEneUt8kiMlbQ63VwyfV0ZOq1cxxqyBvJJCRX3Cm5X7c+LJqQ63+j8N5kXkEIKeiXJl2jLP3/sPf6j257QSbwvmwy9ZD5ED6wd2GF+99J5WZ2S13h39aOetObrdO/A8f/3AdasbWrBEYnkVnzkhs0XpkA8YopUw9H/glEJw4ps49huuRgOzf8n6Iq85PCtneDxfhUCQ+F3JvdileT8FyxdfkCfhI+9yRCSAMlHxt+HLX3pd8+/0mh0MT9fPF8Xg6EeB52sc+WQlyxgA3XJycfi+D84X9GNCUKZ+E/JGjyqqbYJtZpo1ZhsN5ybJxPbXlluSlJMcf++8TIA=='))[32*y+x]*3+i]for i in(0,1,2))

Test code
for y in range(32):
    for x in range(32):
        print(red(x,y), blue(x,y), green(x,y))

Based on solution from Dillon Cower

PHP (5.4) - 822
I've done this deliberately not using any of the built-in compression functions. This solution is not finished, I'm not sure if I've given up, I can see areas for improvement but I can't find the time/willpower to refactor the whole thing at the moment, so I'm posting what I have so far.
Newlines + comments to be removed for 822 bytes.
// Colour map
$c=[0,16354410,4671418,6379596,7783255,5295994,5390379,3435360,9975021,5131894];

// Optimised RLE map
$r=array_merge(array_diff(range(10,89),[27,40,47,56,59,60,63,66,67,70,73,75,76,77,79,80,83,86]),[92,94,99,105,107,112,118,145]);

// Image data (base 70)
$e="CDsF<Fd]WPX<F0^VE0240GX02Fd;d_F0EFN0?;<onFE0H;2>0I404h0NZ@;>0460640>20<0E05050Q@;0GI0Gd`0H@?0eMqCjY?:51Z0QJjYu[ZD>0>:H:50Wk?;:PQ05M0ErDH;`]E0270707?DHg2VW[?DHg<MW[?c0;F032DN:<7:?0V0DX<0E0^K5:D01CXW0X<K7Ub:d03I3<A?Cp0^023I3<A?:T0Ta<>3I420A050B0Bt2G0=GAHbS0\:8i08Hbf9S0iAH9FBf09S>0YAH9=09IaLoAQO9IBA0ABiKQF09@CA03CP04K:H0ObAXK080AQIFT0B08XS:AHRm090BOlHI0";

// Expand image data
for($i=0;$i<352;$i++){$b=$r[ord($e[$i])-48];$l=(int)($b/10);while($l--)$d[]=$c[$b%10];}

// Colour retrieval functions
function red($x,$y){global$d;return$d[$x+$y*32]&0xff;}
function green($x,$y){global$d;return$d[$x+$y*32]>>8;}
function blue($x,$y){global$d;return($d[$x+$y*32]>>8)&0xff;}

Test stub:
for ($y=0;$y<32;$y++) {
    for ($x=0;$x<32;$x++) {
        printf("%d %d %d\n", red($x, $y), blue($x, $y), green($x, $y));
    }
}

The compression of the image data itself is pretty good, but the functions to retrieve RGB values take up 1/4 of the code.
I'm using a custom base70 + run length encoding mechanism.

There are 10 unique colours
Colours have run lengths between 1 and 14 (12 used).
There are 120 possible combinations.
There are only 70 unique run/colour combinations actually used.

The encoded image data references the array index of an RLE, which in turn indexes the array of colours. I'm not sure how much overhead this adds or subtracts over directly referencing the colours.
Sine there are 10 colours (0 to 9), RLEs are stored as run_length * 10 + colour_index. Giving a range of encodings between 10 and 145 without experimenting with optimisations based on colour ordering. (i.e. I could make the range 19 to 140 by moving colours 0 to 5, 5 to 9, and 9 to 0 - but this may have other knock-on effects)
A previous answer states their encoded data is 472 bytes. My encoded image data is 352 bytes, but the intermediate RLE / colour map (which is not binary encoded) is a further 129 bytes, putting the total at 481. (as well as additional overhead for joining up the two). However I suspect my method might scale better for larger images.
TODO:

Investigate binary encoding of RLE map
Find a way of reducing the size of the functions. global is a bitch, but can't access character indexes on constants.
Experiment with colour index ordering to see if RLE map size can be reduced with longer sequential runs of numbers
Potential 64bit specific optimisations of colour map? (r0 << 56 | r1 << 48 | ...)?
Experiment with vertical RLE to see if it results in a more compact set of encodings.
Area encoding?

Julia, 636 bytes
Zlib compression is not part of standard libraries, so I only used Base64 encoding
using Base64
red,blue,green=[(x,y,d=base64decode)->d("AAAAavmMukdHTGFYV3bDelDPK1JAYDRr7Zg0dk5O")[3vcat([fill(div(i,16),i%16) for i=d("AxMrMyIzJxYlRDUiMwEmFSMBIUEBQzUBITMnEidGMwEjMyQBUhIiSSkzIwFTEiFCAWNBAUEoASRVYhJCAUFhAWFBAUIhASIBIwFRAVEBVGISAUNjAUMnVgFTYlIBRxRaA1hFUgJREVUBVHNYRV51VRNCAUICUwJRASV4UhICRFQBURQBI3oTUxJWFiMBIXEBcQFxUhNTGCEVJXVSE1MYIhQldVIXARIzATEhEyQCInECUgEVARM1IgEjASaDUQITAREDNSUBNSKDcQWWAicBMWMxIoJSA5kBJgEhMWMxIoJSApQBlIYiQjFjQSEBggFRAZIBkoshQwEyQ4JTloQBhQKBSAGBU5aHkYQBSIJTkTOShwGRhEIBRYJTkTIBkWOGk0mCVDSRY5KCAYKSSINUMwGRYgOCATEDRAFBgwJTATSWgjWDAYEBglRjM5QBkgGBNYQCglNkmAGRAZI0iFNjAQ==")]...)[32y+x+1]+c] for c=1:3]

Try it online!
Un-golfed version:
colors contains the 10 unique colors
color_enc contains the color number (0-9) in base16 + the amount it should be repeated (1-14) in base 16
color_dec rebuilds the whole image with color numbers (0-9)
using Base64

colors = "AAAAavmMukdHTGFYV3bDelDPK1JAYDRr7Zg0dk5O"
color_enc = "AxMrMyIzJxYlRDUiMwEmFSMBIUEBQzUBITMnEidGMwEjMyQBUhIiSSkzIwFTEiFCAWNBAUEoASRVYhJCAUFhAWFBAUIhASIBIwFRAVEBVGISAUNjAUMnVgFTYlIBRxRaA1hFUgJREVUBVHNYRV51VRNCAUICUwJRASV4UhICRFQBURQBI3oTUxJWFiMBIXEBcQFxUhNTGCEVJXVSE1MYIhQldVIXARIzATEhEyQCInECUgEVARM1IgEjASaDUQITAREDNSUBNSKDcQWWAicBMWMxIoJSA5kBJgEhMWMxIoJSApQBlIYiQjFjQSEBggFRAZIBkoshQwEyQ4JTloQBhQKBSAGBU5aHkYQBSIJTkTOShwGRhEIBRYJTkTIBkWOGk0mCVDSRY5KCAYKSSINUMwGRYgOCATEDRAFBgwJTATSWgjWDAYEBglRjM5QBkgGBNYQCglNkmAGRAZI0iFNjAQ=="

color_dec = vcat([fill(i÷16, i%16) for i in base64decode(color_enc)]...)

red,blue,green=[(x,y)->base64decode(colors)[3*color_dec[32y+x+1]+c] for c in 1:3]

Try it online!
Test code:
for y in 0:31
    for x in 0:31
        println(red(x,y), " ", blue(x,y), " ", green(x,y))
    end
end

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Rotate an ASCII art image
Out of all of the ASCII characters, it is easy to tell that some of them form groups that are rotations of the same basic character. For example, V > ^ <. This allows the possibility to construct ASCII art that can be rotated by multiples of 90 degrees and still remain ASCII art.
The Challenge
Your goal is to golf a program that accepts ASCII art and the number of degrees to rotate it from STDIN, and prints the rotated ASCII art to STDOUT.
On the first line of input, your program will receive a number N. This number represents the width and height of the ASCII art.
You will then receive N more lines of exactly N characters each (the newline is not counted in this number). The size of the art will always be a square, although it may have padding in the form of spaces to make it a square.
You will then receive one more number on a final line: 90, 180, or 270. This represents how many degrees clockwise the picture should be rotated.
Note: The inputted image will only contain characters that can be rotated by the correct amount. If the input does not match these requirements exactly, no specific behavior is required.
As output, your program should print exactly N lines of N characters, with newlines after each line. The image should be rotated so that each character in the original has been replaced by a rotated version and has been moved to the correct place in the image.
Examples (not very beautiful ASCII art)
Input
5
<- ||
|  |V
+->+
   |O
<--+
90

Output
^ +-^
| | |
| V
+-+--
 O <-

(Rotations by 90 and 270 won't look very good because the characters are not squares)
Input
6
+ /\ +
| \ \|
(  \/|
 \   )
I \ /
:) V $
180

Output
$ ^ (:
 / \ I
(   \
|/\  )
|\ \ |
+ \/ +

Required Supported Characters
For all rotations (90, 180, and 270), the program should be able to rotate:

Spaces, +, @, X and O which never change
V > < ^
| - and \ / (rotated by 180 they stay the same)

For 180 degree rotation, these additional characters must be supported

I N Z % : 0 = S ~ $ # which stay the same
P d, ( ), [ ], { }, M W, and 9 6

Your first example contains the lowercase v, which is not a supported character. I assume it was meant to be an uppercase V. Also, the last line in it is not padded to be 5 chars long.

@IlmariKaronen Good catch. It's fixed now.

P d, ( ), [ ], { }, M W, and 9 6 can ever be turned 90º or 270º?

No, the art will only contain characters that are designated to be able to rotate the correct amount. The last two bullets list characters can be rotated by 180º only. Your program will not be asked to rotate these by any other amount.

GolfScript, 79 75 73 67 chars
n%(;)~90/{-1%zip{{.'V<^>P(d)[{]}M9W6/\/\|-|'4/\+{.}%n+.@?)=}%}%}*n*

Looks like my and Peter Taylor's solutions are experiencing a certain amount of convergence.  Anyway, looks like I'm still a few chars ahead for now. :-)  Thanks (and +1) to both Peter and copy for ideas that I've shamelessly stolen.
This code completely ignores the size given on the first line, since it's redundant information.  It should even handle inputs with non-square dimensions, but it very much depends on all the input lines being padded to the same length.  Trying to rotate the characters P, d, (, ), [, ], {, }, M, W, 9, or 6 by 90 or 270 degrees may produce unexpected output; all other characters that are not explicitly remapped are retained unchanged.
Ps. Here's my original 79-char solution:
n%(;)~90/:z{-1%zip}*n*z'V<^>/|-\V>^<'{:c;{{.c?~.c=@if}%}*}:s~2z='P([{M96W}])d's

Convergence? :P I liked your trick for doing the lookup without repeating (many) characters, but it doesn't seem to be compatible with my trick for avoiding the if.

C, 336 chars
I'm sure there's room for improvement.
char*a="<^>V|-|-/\\/\\ppdd(())[[]]{{}}MMWW9966",*p,*q;
n,x,y,r;
z(c){
    return(q=strchr(a,c))?a[(q-a&-4)+(q-a+r&3)]:c;
}
#define A(r)(r&3^3?1-r%4:0)*
f(r){
    return A(r)x+A(~-r)y+(r&2)/2*~-n;
}
main(){
    scanf("%d\n",&n);
    p=q=malloc(n*n+1);
    for(y=n;y--;q+=n)gets(q);
    scanf("%d",&r);
    for(r/=90;++y<n;puts(""))for(x=0;x<n;x++)putchar(z(p[f(r)+n*f(r+1)],r));
}

Golfscript (80 79 78 77 76 chars)
n%(;)~90/{zip{-1%{'V<^>V|-|/\/''Pd()[]{}MW96'{.4*}%4/128,+{.}%+.@?)=}%}%}*n*

NB Entering the "undefined behaviour" permitted by invalid input can produce somewhat curious output, because of placeholder characters (outside ASCII) used for certain characters whose rotation by 90 degrees is not defined. For example, ( would be mapped to code point 160, which in ISO-8859-1 and Unicode is a non-breaking space.

javascript (181 chars)
a=prompt(f="V<^>V|-|/\\/P(d)P([{]}[}M9W6M9").split(n="\n");c=a.pop()/90;for(
b=a[0];c--;a=d.split(n))for(e=d=n;e<b*b;++e%b||(d+=n))d+=f[f.indexOf(g=a[b-e
%b][e/b|0])+1||a]||g;alert(d)

Requires every line to be padded to the given length.

can you give me an example of what exactly I need to put on prompt? I tried replacing lines with \n, normal copy paste and balancing spaces to the first/last lines and failed to make it work

@ajax333221 Pasting multiple lines into an alert box only works in Chrome, I just noticed for the first time. Also make sure you're not copying a final newline.

Canvas, 7 bytes
╶╶90┤÷↷

Try it here!
basically cheating


text:
shortest progam to scan a line and print it using befunge!
well, I'm newly introduced to befunge.
it seems to be an amazing language but a bit hard to start with! anyway after about 2 hours of hard work I've created a code which could read a line from stdin and write same line into stdout(I'm using line -1 as buffer in this code):
0> :~:a-#v_$$v vg-10:-1< >$>:#,_@
 ^+1p-10\<   >0>\:    #^_^

since I'm new to this language I wanted to know if there is a shorter code to do such a thing.
I'm currently using Rc/funge-98 v2 interpreter. note that none-trailing whitespaces are counted in your code.

since it seems no one could create 7 character program, here is what I did. it works at least with befunge!
Befunge, 7
~:,a`j@

@ajax333221 here is my code.

but this does not output the newline.

@marinus that's no big deal, just putting "," at the third character will solve that! the whole idea is to use "j" instead of "!#@_"

Befunge-98, 4
~,#@
Try it online!
It works because ~ acts like r when there is no more input (credit to David Holderness for finding this in the funge-98 spec)

Befunge, 10
~:,a`!#@_

You were thinking a bit too hard about it I think :)

now I see what you did there, it seems to be complete answer. I was going to later use input string to parse as a "single precision floating point", which seems to be not possible using your method.

the only reason I'm not accepting your answer is because I know an answer of 7 characters.

@Gajet you should post it

@ajax333221 I want to give other people opportunity to get 15 rep.