Excel - Select/change value for same cell in multiple sheets (if they exist) in same workbook Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
jarhead
Posts: 151
Joined: 09 Sep 2020, 12:43

Excel - Select/change value for same cell in multiple sheets (if they exist) in same workbook

Post by jarhead » 07 Dec 2021, 12:43

I process multiple Excel files per day. Each workbook typically has two sheets. The first sheet is a cover page so I don't change anything. Cell B1 of the second sheet contains a SSN without dashes (333224444). I run the following script that takes the SSN and replaces the first five numbers with an X:

Code: Select all

x1 := ComObjActive("Excel.Application")
cell2 := x1.Sheets(2).Range("B1") 
cell2 .value := RegExReplace(cell2.text, "\d{5}", "XXXXX")
With a recent change to the generated Excel files I receive, workbooks can now have between two to four sheets. What is the best way to run the above script on all sheets beginning with the second sheet if they exist? There is always a second sheet but not always a third or fourth. So sheets 2-4 all contain the SSN in cell B1. Thanks!

User avatar
mikeyww
Posts: 26871
Joined: 09 Sep 2014, 18:38

Re: Excel - Select/change value for same cell in multiple sheets (if they exist) in same workbook

Post by mikeyww » 07 Dec 2021, 12:52

Code: Select all

XL := ComObjActive("Excel.Application")
Loop, 3
 Try cell2 := XL.Sheets(A_Index + 1).Range("B1"), cell2.Value := RegExReplace(cell2.Text, "\d{5}", "XXXXX")

User avatar
flyingDman
Posts: 2817
Joined: 29 Sep 2013, 19:01

Re: Excel - Select/change value for same cell in multiple sheets (if they exist) in same workbook  Topic is solved

Post by flyingDman » 07 Dec 2021, 13:01

For all sheets (if they exist) other than the 1st one:

Code: Select all

xl := ComObjActive("excel.application")
for sheet in xl.sheets
	if (a_index > 1)
		sheet.range("B1").value := "xxxxx" substr(sheet.range("B1").text,6)
14.3 & 1.3.7


User avatar
flyingDman
Posts: 2817
Joined: 29 Sep 2013, 19:01

Re: Excel - Select/change value for same cell in multiple sheets (if they exist) in same workbook

Post by flyingDman » 07 Dec 2021, 14:10

Because there is always an other way:

Code: Select all

xl := ComObjActive("excel.application")
for sheet in xl.sheets
	(sheet.index > 1) && sheet.range("B1").value := "xxxxx" substr(sheet.range("B1").text,6)
14.3 & 1.3.7

Post Reply

Return to “Ask for Help (v1)”