title: VBA code in command button doesn't work on button click
body: <p>I'm don't know VBA and I'm only doing this out of necessity so forgive me. I normally just do T-SQL.</p>
  
  <p>I found the following code in a help article to take data from an Excel sheet and output it into a txt file which will be used to run through Scribe. So far;</p>
  
  <ol>
  <li>I've placed the Command button on the sheet</li>
  <li>I've right clicked to View Code</li>
  <li>I pasted the code from the article into the VBA editor and adapted parts of it for my needs (the file path basically)</li>
  </ol>
  
  <p>When I run the code from the editor it performs perfectly.</p>
  
  <p>When I close the editor and click the button on the sheet it runs but the resulting text file is just the appropriate number of empty strings in the text file. It's like it can see the number of rows that have data but not the actual data in the cells.</p>
  
  <p>Have I missed something obvious? I can't see anything more in the help article (which isn't really written for complete novices I have to say) that would solve the problem!</p>
  
  <pre><code>Sub CommandButton1_Click()
  
  Dim FilePath As String
  Dim rng As Range
  Dim CellData As String
  Dim LastCol As Long
  Dim LastRow As Long
  
  LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
  
  LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
  
  Set rng = Worksheets("Discount Template").Range("B3")
  
  FilePath = "\\SERVER2012\IT Dept\AccessSupplyChain\Product Discount Uploads\" &amp; rng.Value &amp; "_" &amp; Format(Now(), "yyyymmdd hhmmss") &amp; ".txt"
  
  Open FilePath For Output As #2
  
  For i = 1 To LastRow
  
      For j = 1 To LastCol
  
          If j = LastCol Then
          CellData = CellData + Trim(ActiveCell(i, j).Value)
  
          Else
  
          CellData = CellData + Trim(ActiveCell(i, j).Value) + ","
  
      End If
  
  Next j
  
  Print #2, CellData
  CellData = ""
  
  Next i
  
  Close #2
  MsgBox ("Done")
  
  End Sub
  </code></pre>