Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all 88809 articles
Browse latest View live

How to Find, cut, paste and erase with VBA code

$
0
0

I am new on VBA and i dont know almost nothing. I've been trying a code to find a value entered in a inputbox "CXRG", find on sheet "ESTOQUEV" cut all the line and paste on sheet "SAIDA" (down from another values) and erase the blank line from "ESTOQUEV"

Someone could help me?

Private Sub CommandButton1_Enter()

linha = Worksheets("SAIDA").Range("A100000").End(xlUp).Row + 1

Worksheets("SAIDA").Cells(linha, 1) = CXOS.Value

Worksheets("SAIDA").Cells(linha, 2) = CXRG.Value

CXOS.Text = ""
CXRG.Text = ""

SendKeys "{TAB}", True    ' Envia TAB para pular par o inicio.

Call refresh.Macro8
End Sub

How do I count unique rows/values based on combination of variables (across columns)

$
0
0

Screenshot of Audit data in Excel

How would I count (unique) rows where at least 1 of the work code categories (the numbers to the right of the column 'Work Code Description') = 1?

E.g. if I selected work codes '1, 6, 95, 99', how could I count the rows (only once) where at least one of these columns had a 1 in the relevant columns?

Taking a user defined equation and using it in a VBA sub to calculate numerical values

$
0
0

I'm currently working on a program to do 4th order Runge Kutta calculations for ordinary differential equations., one of the requirements for the program is that the user will input the equation they want the 4th order operation to calculate. Is there a way to take the user inputted equation from a specific cell and use it in VBA sub to calculate the new y values?
The equations are going to be multi-variable polynomial equations containing x and y. This is the loop I am hoping to use to perform the calculation, where equa is currently a function with a pre-established equation for testing, but is planned to be the user inputted equation.


n = (xf - xi) / h

For i = 1 To n
    k1 = equa(x, y)
    y1 = y + k1 * h / 2

    k2 = equa(x + h / 2, y1)
    y2 = y + k2 * h / 2

    k3 = equa(x + h / 2, y2)
    y3 = y + k3 * h / 2

    k4 = equa(x + h, y3)

    yf = y + ((k1 + 2 * k2 + 2 * k3 + k4) * (1 / 6) * h)

    Cells(7 + i, 1).Value = y

    x = x + h
Next i

Phpexcel create wrong file

$
0
0

this is my simple code to create an xlsx file and open it with openoffice

require(APPPATH.'/PHPExcel-1.8/Classes/PHPExcel.php');
require(APPPATH.'/PHPExcel-1.8/Classes/PHPExcel/Writer/Excel2007.php');
$this->load->library('excel');
$objPHPExcel = new PHPExcel();

$objPHPExcel->setActiveSheetIndex(0)
   ->SetCellValue('A1', 'Calendario Attivit');

$filename = "prova".".xlsx";
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Disposition: attachment;filename="'.$filename.'"');
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');  
$objWriter->save('php://output');
exit;

the file is downloaded but when open it i get this:

enter image description here

someone can help me ?

Fail to get csv from S3 and convert it with Python

$
0
0

I need to read csv file from s3 bucket and insert each row on dynamoDB

def load_users_dynamodb():

s3 = boto3.client('s3')
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table("test")

obj = s3.get_object(Bucket='test-app-config', Key='extract_Users.csv')
#return obj
data = obj['Body'].read().split('\n')

#return json.dumps(data)

with table.batch_writer() as batch:
    for row in data:
        batch.put_item(Item={
            'registration': row.split(',')[0],
            'name': row.split(',')[1],
            'role': row.split(',')[2],
            'company': row.split(',')[3],
            'hiredcompany': row.split(',')[4],
            'region': row.split(',')[5]
        })

return 'OK'

im getting exception and I can't proceed:

   Response:
{
  "errorMessage": "a bytes-like object is required, not 'str'",
  "errorType": "TypeError",
  "stackTrace": [
  "  File \"/var/task/lambda_function.py\", line 10, in          lambda_handler\n    'body': load_users_dynamodb()\n",
"  File \"/var/task/lambda_function.py\", line 21, in load_users_dynamodb\n    data = obj['Body'].read().split('\\n')\n"
]
}

Someone can help me please? o/

Convert many table to excel columns

$
0
0

I create web app for article review.

I have table named Article and each Article have some ArticleReview:

Article

ArticleId
ArticleTitle  
NumberOfComment
NumberOfView
...
ICollection<ArticleReview> Reviews   

Admin can add many user (I call them JueryUser) and send article to them for review, I use table named ArticlePoint for adding/removing User's that can review each Article:

ArticlePoint

public int ArticlePointId { get; set; }
public DateTime CreateOn { get; set; }
public string Id { get; set; }      // Id of User that review Article
public ApplicationUser JuryUser { get; set; }
public string UserId { get; set; } // Id of User that write Article
public int ArticleId { get; set; }
public string JuryReview { get; set; }

When Jury user review article he/she gave article some point, this points is based on question's that provided by Admin, this review's are stored in ArticleReview table.

ArticleReview

ArticleReviewId 
ReviewPoint
ArticleId
ReviewerId

As I said in my previous question I want to get excel export from summery of point that gave to articles by each juery.

I use this below code to generate my excel file:

public static class ExcelExportHelper
    {
        public static string ExcelContentType => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        public static DataTable ListToDataTable<T>(List<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dataTable = new DataTable();

            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
            }

            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }

                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

        public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
        {
            byte[] result = null;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
                workSheet.View.RightToLeft = true;
                int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;

                if (showSrNo)
                {
                    DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
                    dataColumn.SetOrdinal(0);
                    int index = 1;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        item[0] = index;
                        index++;
                    }
                }

                // add the content into the Excel file  
                workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
                // format header - bold, yellow on black  
                using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
                {
                    r.Style.Font.Color.SetColor(System.Drawing.Color.White);
                    r.Style.Font.Bold = true;
                    r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb5ad"));
                }

                // format cells - add borders  
                using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
                {
                    r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Right.Style = ExcelBorderStyle.Thin;

                    r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
                }

                if (!String.IsNullOrEmpty(heading))
                {
                    workSheet.Cells["A1"].Value = heading;
                    workSheet.Cells["A1"].Style.Font.Size = 20;

                    workSheet.InsertColumn(1, 1);
                    workSheet.InsertRow(1, 1);
                    workSheet.Column(1).Width = 5;
                }

                result = package.GetAsByteArray();
            }

            return result;
        }

        public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
        {
            return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
        }
    }

and use this code in my action method:

  public ActionResult ExportToExcel()
        {
            byte[] filecontent;
            try
            {

                var juryLists = from user in db.Users
                                where user.Roles.Any(r => r.RoleId == "IdOfRole")
                                select user;

                var articles = db.Articles.Include(r=>r.ArticleReview).Where(r2=>r2.ArticleReviews.Any()).ToList();

                List<string> cmnList = new List<string>();
                cmnList.Add("Article Title");
                cmnList.Add("Point Avarage");
                var juryListNames = juryLists.OrderBy(x=>x.Id).Select(x => "JuryPoints : " + x.FullName).ToList();
                cmnList.AddRange(juryListNames);
                string[] columns = cmnList.ToArray();

                var heading = $"Results";

                var dt = new DataTable();
                foreach (var column in columns)
                {
                    dt.Columns.Add(column, typeof(string));
                }

                foreach (var item in articles)
                {
                    var _obj = new object[] { item.ArticleTitle, item.ArticleReviews.OrderBy(x=>x.JuryUserId).Select(x=>x.ArticlePoint).Average() }.Concat(
                        item.ArticleReviews.OrderBy(x => x.JuryUserId).GroupBy(x => x.JuryUserId).Select(x => x.Average(y => y.ReviewPoint))
                            .Cast<object>()).ToArray();
                    dt.Rows.Add(_obj);
                }
                filecontent = ExcelExportHelper.ExportExcel(dt, heading, true, columns);
            }
            catch (Exception e)
            {
                return RedirectToAction("Details",new {id= id });
            }


            return File(filecontent, ExcelExportHelper.ExcelContentType, "Results.xlsx");
        }

My Problem:
I create header for my excel but problem is some jury user wont gave point to article yet and when I generate excel, point of another jury placed in column of another one.
ex: one article sent to 5 jury jury 1,2 and 5 give point to article but after export point of 5th jury place in 3th jury column how can I resolve this?

How to show (or prevent hiding) Excel worksheets created from PowerShell

$
0
0

I have a script that does a lot of Excel processing. After making two worksheets, I then make three more and populate them with data. However, when I open that Workbook, sheets are in the order of 5, 4, 3, 1, 2

Open the spreadsheet

$ExcelObject=New-Object -ComObject Excel.Application
$ExcelWorkbook=$ExcelObject.WorkBooks.Open("c:\Output.xlsx") 

Make a worksheet

$ActiveWorksheet=$ExcelWorkbook.WorkSheets.Add()
$ActiveWorksheet.Activate()
$ActiveWorksheet.Visible=$True
$ActiveWorksheet=$ExcelWorkbook.WorkSheets.item("$WorksheetName")

It looks like the three last worksheets don't exist until you click the left worksheet navigation arrow three times to make them appear.

If I record a macro, the VBA code to make them visible is three instances of

ActiveWindow.ScrollWorkbookTabs Sheets:=-1

There is the xlFirst enumeration, but I can't seem to find the right syntax to get that working.

Why are they not showing? Is there a Powershell way to make them visible or to scroll them to show before saving?

Importing Data from Access into Excel weekly using ADO

$
0
0

I am trying to automate a data pull from Access into Excel using ADO. Each week I pull in the previous weeks deals from Monday-Friday. Right now I have SQL pulling in the deals from the previous week, however the way I have it right now I would manually have to change the dates in the code each week. Is there a way to do this automatically?

Below is the code I currently have:

Sub Import()
  'Declaring the necessary variables
  Dim cn As ADODB.Connection
  Dim rs As ADODB.Recordset
  Dim dbPath As String
  Dim SQL As String
  Dim i As Integer
  Dim var As Range

  cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;"& _
  "Data Source=xxx"'create the SQL statement to retrieve the data from the table
  sSQL = "SELECT * FROM BP_Closed_Deals WHERE Start_Date between '10/21/2019' and '10/25/2019'"'create the ADODB recordset object
  Set rs = New ADODB.Recordset

  'connectionString open
  rs.Open sSQL, cn, adOpenForwardOnly, adLockReadOnly, adCmdText

  If Not rsData.EOF Then
      Sheets("Deals_2018_Copy").Range("A2").CopyFromRecordset rsData
      rsData.Close

       Else
       rsData.Close
       MsgBox "Error: No records returned", vbCritical
   End If

   Set rsData = Nothing


  End Sub


Extract financial fundamental from Yahoo finance with excel

$
0
0

Yahoo changed his structure for the financials (fundamental) report. In the past (last month) at the page https://finance.yahoo.com/quote/AAPL/financials?p=AAPL&guccounter=1 I could download the information regarding the financial Income Statement or Balance Sheet or Cash Flow in VBA Excel as a table. Now they have updated the "new" version that appears as a table but I cannot extract it con VBA Excel. There someone that can help me? If you need I can post the code in VBA regarding the old version, that can download all the tables in the HTML page.

To better explain I need the information in the yellow box. enter image description here You can see that it appears as a table, but if you look inside in the HTML code there is not the normal tag regarding tables. I identify that the starting "table" has this tag <div class="D(tbrg)" but I don't know how to proceed to extract data. The same "table" is in the Balance Sheet and Cash Flow selection.

Thanks in advance

@asher, I tried your macro, but I received the following error: enter image description here and in the debag the problem is in: enter image description here Thanks a lot for your help

How do I extract column cells as single pictures?

$
0
0

I need to save pictures based single cells within a column which has Chinese characters in it as separate JPGs for inclusion in a Visual FoxPro report.

I have pored through various Stack Overflow questions, such as: Saving range as picture with Excel 2016 and Export pictures from excel file into jpg using VBA However, I'm relatively new at VBA, and I cannot figure out how to iterate through the table to make individual JPGs for each cell (and name them separately as well). Ideally, I would like to name them with the value of another column, but I can also live with naming then with the record number (i.e. 1.jpg, 2.jpg...). I tried making code from another post work (see below), but I haven't had any luck.

Sub makepic()
    Dim path As String
    path = "C:\BP\BP2020\JPGs\"
    Dim cntr As Integer
    cntr = 1
    Dim rgExp As Range
    CCntr = CStr(cntr)
    CString = "A1:A6"
    Set rgExp = Range(CString)
    For Each cell In rgExp
      cntr = cntr + 1
      rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
      With ActiveSheet.ChartObjects.Add(Left:=rgExp.Left, Top:=rgExp.Top, _
        Width:=rgExp.Width, Height:=rgExp.Height)
        .Name = "ChartVolumeMetricsDevEXPORT"
        .Activate
      End With

      ActiveChart.Paste
      ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Chart.Export (path + CCntr & ".jpg")
      ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Delete
   Next cell
End Sub

The main error message I was getting concerned "shapes," however I'm not looking at copy pictures out, but to save text in each cell as pictures.

PS: I try to make my questions as succinct and readable as I can, but I am continually getting told I am not phrasing my questions right. This is evidently due to ignorance of the correct format. I have re-read the articles on posting and hope this one "passes muster." If not, I apologize.

Excel VBA stop code where conditions are met

$
0
0

I'm struggling getting my code to work.

I have a button on the excel sheet that when triggers

  1. checks required fields value is 0, if not then message box and end code

  2. checks if the reference number already exists on a master tab, if the reference exisits, message box and end code

  3. if 1 and 2 pass then perform a copy and paste as values for 3 ranges then message box.

I've tried a number of options but can't get it to work

    Function Mand() As Boolean
   'checks that mandatory fields have been updated

   If Sheets("INPUT").Range("C11") > 0 Then MsgBox "Mandatory Fields Missing"& vbNewLine & "Changes Not Saved!"
   Mand = True

    End Function


    Function RecEx() As Boolean
    'checks that the reference number does not exisit on the High Level master list

    dup = WorksheetFunction.CountIf(Sheets("High_Level_List").Columns(1), Sheets("INPUT").Range("C17"))
    If dup > 0 Then MsgBox "This Record Exists!!!"& vbNewLine & "If saving an update, use the Save Changes button"
    RecEx = True   

    End Function


    Sub RegisterNewRec()
    ' checks 2 functions, if either are TRUE then exit, otherwise update master

    If Mand Then Exit Sub

        If RecEx Then Exit Sub

    End If

    Dim rng As Range
    Set rng = Sheets("INPUT").Range("AO2:CX2")
    Sheets("High_Level_List").Range("A"& Rows.Count).End(xlUp).Offset(1).Resize(rng.Rows.Count, rng.Columns.Count).Cells.Value = rng.Cells.Value

    'more code that updates master

    MsgBox "Record added to Master"

    End Sub

Return Index Position Where First Corresponding Cell Value is Blank - Excel

$
0
0

enter image description here

I have two rows side by side in Excel and I want to return the index location (top row) where the first cell in the bottom row has a blank value. In this example, the index cell would be 9.

I've tried match is blank and index match without luck. Any help would be appreciate.

=INDEX(O3:AE3,MATCH(FALSE,ISBLANK(O3:AE3),0))

How to insert cell values before existing cell values in VBA

$
0
0

I have a code in VBA, which copies 2 columns of existing values below an another sheet's similar data. I want to slightly change the VBA code to, that if the cell of value another sheet (C3) is TRUE, then it copies that data to the beginning of the existing data instead (the beginning is A1 and B1). I have this data in a worksheet:

-Q-  -R-
156  F5
486  T9
695  H3

I have an already existing data in an another worksheet:

-A-  -B-
695  E6
326  T8
326  Q9

I need to paste the new values before the existing values if the value of C3 on another sheet is TRUE

-A-  -B-
156  F5
486  T9
695  H3
695  E6
326  T8
326  Q9

I have the code to copy the data to the end of the existi8ng data, I just need to expand this to be able to insert the data to the beginning of the data, essentially shifting all existing values below the new ones if C3 is TRUE. (the Values I need to copy is in the "Nastavit D" sheet (Q and R), I need to paste them into the "Chain (A and B), and the C3 TRUE cell is on the "Nedotykat sa!!!" sheet) (If C3 is FALSE, I need to copy it to the end of the existing data, which my code already does, without the C3 check.)

Sub CopyRange()
    Dim x, y(), I As Long, ii As Long

    If Sheets("Nastavit D").[Q2] = "" Then Exit Sub
    x = Sheets("Nastavit D").[Q2:R1000]
    For I = 1 To UBound(x, 1)
        If x(I, 1) <> "" Then
            ReDim Preserve y(1 To 2, 1 To I)
            For ii = 1 To 2
                y(ii, I) = x(I, ii)
            Next
        Else: Exit For
        End If
    Next
    With Sheets("Chain")
        .Cells(.rows.Count, 1).End(xlUp).Offset(1, 0).Resize(UBound(y, 2), 2) = Application.Transpose(y)
    End With

End Sub

How to count up elements in excel

$
0
0

So I have a column called chemical formula for like 40,000 entries, and what I want to be able to do is count up how many elements are contained in the chemical formula. So for example:-

EXACT_MASS  FORMULA
626.491026  C40H66O5
275.173274  C13H25NO5

For this, I need some kind of formula that will return with the result of

C  H  O
40 66 5
13 25 5

all as separate columns for the different elements and in rows for the different entries. Is there a formula that can do this?

Token Comma expected - can not run JSON query

$
0
0

This is a problem i have working in Excels Power Query. I have this query saved in a variable named "content" which is passed to the call Web.Contents.

I can not run the query, i get "Token Comma expected" error. Can somebody tell what that is about?

`let
content = "{
"query": [
    {
      "code": "Region",
      "selection": {
        "filter": "vs:RegionKommun07",
        "values": [
          "1283"
        ]
      }
    },
    {
      "code": "Sysselsattning",
      "selection": {
        "filter": "item",
        "values": [
          "FÖRV"
        ]
      }
    },
    {
      "code": "Alder",
      "selection": {
        "filter": "item",
        "values": [
          "30-34"
        ]
      }
    },
    {
      "code": "Kon",
      "selection": {
        "filter": "item",
        "values": [
          "1"
        ]
      }
    },
    {
      "code": "Tid",
      "selection": {
        "filter": "item",
        "values": [
          "2015"
        ]
      }
    }
  ],
  "response": {
    "format": "px"
  }
}",
Source = Json.Document(Web.Contents("http://api.scb.se/OV0104/v1/doris/sv/ssd/START/AM/AM0207/AM0207H/BefSyssAldKonK", [Content=Text.ToBinary(content)]))
in
    Source`

VBA Selecting Multiple File Paths and Saving in Cells

$
0
0

I can save one file path to my desired cell, I would like to be able to save more than one at a time. I have tried to change the code, yet I can't figure out how to save on the next row it just saves it all on the same line.

Dim FileFldr As FileDialog
Dim FileName, OrigFilePath, FileType, FilePath, CustID As String
Dim LastAttRow As Long
Dim vrtSelectedItem As Variant
CustID = txtID.Value
Set FileFldr = Application.FileDialog(msoFileDialogFilePicker)

With FileFldr
   .AllowMultiSelect = True
   .Title = "Select file to attach"
   .Filters.Add "All Files", "*.*", 1
   If .Show <> -1 Then GoTo NoSelection

   For Each vrtSelectedItem In .SelectedItems
   Next

    FilePath = .SelectedItems()
    FileName = Dir(FilePath)
    FileType = Right(FileName, Len(FileName) - InStr(Dir(FileName), "."))

   With Sheet6
        LastAttRow = .Range("D9999").End(xlUp).Row + 1 
        .Range("D"& LastAttRow).Value = CustID 
        .Range("E"& LastAttRow).Value = FileName
        .Range("F"& LastAttRow).Value = FileType
        .Range("G"& LastAttRow).Value = FilePat
        .Range("H"& LastAttRow).Value = "=Row()"

   End With 
   NoSelection:
   End With 
   Sheet6.Activate

End Sub

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

$
0
0

How can I use regular expressions in Excel and take advantage of Excel's powerful grid-like setup for data manipulation?

  • In-cell function to return a matched pattern or replaced value in a string.
  • Sub to loop through a column of data and extract matches to adjacent cells.
  • What setup is necessary?
  • What are Excel's special characters for Regular expressions?

I understand Regex is not ideal for many situations (To use or not to use regular expressions?) since excel can use Left, Mid, Right, Instr type commands for similar manipulations.

Variable isn't set unless debug.print executed first

$
0
0

On my sheet, I click a button, the button fires the below Sub. Which is supposed to read the row and col of the clicked button location, then pop up a message box the with the content of a hidden cell on the same row.

When this code executes, the ipf variable always remains as the string "initial" unless I add a debug.print statement. I can debug.print any of the variables (ipf, row_no, col_no) and the ipf variable is set fine.

After I've added debug.print, clicked the relevant button to get the right result, then removed debug.print, it continues to work until I reload the sheet.

I've tried casting as a string in case that is the problem, but I simply do not understand why it's doing this.

Essentially, the sheet is filled with up to three buttons on each row, when one of those buttons is clicked, this code grabs the row and col of the clicked button to pull the value of the cell, which will be one of three strings; "Initial", "Prelim" or "Final". Using that string (in the ipf variable) it will fall into one of the cases to pull a string from another cell on that row to show in a message box.

Unless the debug.print is there, the ipf var is always"Initial".

Public Sub showDefinitionMsgBox()
    Dim obj As Object, _
        oGlobals As clsGlobals, _ ' Class that contains project-wide things. Access to sheets and often used variables.
        row_no As Long, _
        col_no As Long, _
        wsMain As Worksheet 'This is the worksheet were using

    ' Get the row and column of the clicked button
    Set oGlobals = New clsGlobals
    Set obj = ActiveSheet.Buttons(Application.Caller)
    row_no = obj.TopLeftCell.row
    col_no = obj.TopLeftCell.column

    ' Grab the name (e.g. INitial, Prelim, Final)
    ' When a button is clicked, we pull the value from the cell under the button.
    ' It will be either "Initial", "Prelim" or "Final"
    Set wsMain = oGlobals.wsMain
    Dim ipf As String
    ipf = CStr(wsMain.Cells(row_no, col_no).Value)

    ' Get the element name
    ' This simply get's a string, which is the name of the row
    Dim element As String
    element = wsMain.Cells(row_no, 12).Value

    ' Withouth this, ipf is _always_ "initial"
    Debug.Print ipf

    ' Pull the text from the dictionary
    ' 13 = init, 14 = prelim, 15 = final
    ' Using the above ipf variable, set the message text as the content
    ' of another cell in the wsMain sheet.
    Dim message As String
    Select Case ipf
        Case "Initial":
            message = wsMain.Cells(row_no, 13).Value
        Case "Prelim":
            message = wsMain.Cells(row_no, 14).Value
        Case "Final":
            message = wsMain.Cells(row_no, 15).Value
        Case Else
            message = "Cannot find that element type:"
    End Select


    ' Show the message box
    ' @TODO: Update this to UserForm for more space
    MsgBox message, vbOKOnly, element
End Sub

I expect the value from the correct cell to appear in the msgbox, but I always get the value from the first case, unless I add the debug.print line.

Error creating table in VBA Excel

$
0
0

So I am importing a bunch of data into a sheet and then I want to make it into a table. I do not know how many rows of data there will be. This code was working correctly a few days ago, but I suppose I might have unwittingly changed something. Here is the code:

Sheets("Enrollment Data Aggregate").ListObjects.Add(xlSrcRange, Range([A1].End(xlDown), "$n$1"), , xlYes).Name = "EDA_Table"

I am getting an error message that says "The worksheet data for a table needs to be on the same sheet as the table." As far as I know, I am making the table on the same page as where the data is. Any suggestions?

Programmatically Install Add-In VBA

$
0
0

I'm looking to create a macro that'll install an add-in for the user to the excel ribbon. I'm upto:

Private Sub Workbook_Open()

On Error Resume Next
Application.AddIns("Name of Addin").Installed = False
On Error GoTo 0

With Application
    .AddIns.Add "Filepath to addin in shared location", False
    .AddIns("Name of Addin").Installed = True
End With

ThisWorkbook.Close False

End Sub

Once running the macro, the addin installs to the ribbon no problems. The issue is, once excel is closed down, the addin no longer shows in the ribbon.

It would appear that excel is expecting the addin to be copied into the users C:\Documents and Settings\Username\Application Data\Microsoft\AddiIns folder as it throws the error that it can't find it when starting excel after closing down.

Now my understanding is that the second (false) variable for the line of code below basically says that the addin shouldn't be copied to the AddIns directory and rather should stay in the shared location.

.AddIns.Add "Filepath to addin in shared location", False

Any ideas on why Excel is expecting the addin to be in the users default folder?

Viewing all 88809 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>